jQuery selector for .parent().parent() - jquery-selectors

Given a series of a form's Label and Input elements like:
<div class="labelEditwrap">
<div class="editor-label">
<label for="Address">Address</label>
</div>
<div class="editor-field">
<input class="text-box single-line" id="Address" name="Address" type="text" value="" />
<span class="field-validation-valid" data-valmsg-for="Address"></span>
</div>
</div>
I'm trying to select the outer most div when the textbox gets focus so I can highlight both label and input:
$("input").focus(function () {
$(this).parent().parent().addClass("curFocus")
});
I've tried a few combinations including:
$(this).parent().parent() // seems the most obvious
$(this).parent().parents("div:first")
Another question here asking about .parent().parent() was solved by finding a syntax error unrelated to the selector. However, in this case, I can see my hightlighter class if I go up only one parent level (only highlights the editor's div) and also if I climb 3 levels (highlights the container holding the full form).
thx
OK....its not the selector. All the suggested alternates (and the original) are correctly 'selecting' the outside wrapper div. The problem was the CSS and how Floats are being applied to the Label and Editor divs. This CSS will produce correct highlighting and also let the label/editor fields align themselves correctly. [whew]
Up to you guys the best way to close/edit/retitle the question in hopes of helping other avoid my 4 hour toubleshooting ordeal.
-highly appreciate the time taken-

Possible Solutions:-
$('.text-box').live('focus', function(){
$(this).parent().parent().css('border', '1px solid red');
});
$('.text-box').live('blur', function(){
$(this).parent().parent().css('border', 'none');
});
or
$('.text-box').bind('focus', function(){
$(this).parent().parent().css('border', '1px solid red');
});
$('.text-box').bind('blur', function(){
$(this).parent().parent().css('border', 'none');
});

The solution you suggested should work correctly
$(this).parent().parent();
I think the issue here is that your event is being bound before there is an object to bind it to. Have you bound your function on document ready?
Something like:
$(function(){
$("input").focus(function () {
$(this).parent().parent().addClass("curFocus")
});
});
Otherwise using 'live' or 'on' to bind the event will work dynamically.
so like:
$('input').live('focus', function(){
$(this).parent().parent().addClass("curFocus");
});

Related

jQuery.on() for children with no particular selector

I have HTML structure like this:
<div class="parent">
<div class="child">
<div class="something">...</div>
</div>
<div class="child">
<div class="something-else">...</div>
</div>
<div class="child">
...
</div>
...
</div>
I catch events (like click) on .child elements like this:
$('.parent').on('click', '.child', function() { ... });
However, I would like to get rid of explicit class specification and base on the fact of direct ancestry itself.
I want to write the code which would not require any particular classes for children elements. Closest thing to this is:
$('.parent').on('click', '*', function() { ... });
But obviously such handler will spread on deeper descendants (.something, .something-else etc.), not only on the first level.
Is there a way to acheive what I look for, being it using something instead of * or some other way?
P.S. I don't want to use direct binding - $('.parent').children().click(function() {...}); - as it is slower and will not work in case of children being dynamically added.
The selector sought for is > *:
$('.parent').on('click', '> *', function() { ... });
(The actual solution was suggested by Josh Crozier in the comments, I just reposted it as an answer.)

Whenever I apply autocomplete.js the input text box will change Algolia

Im using algolia to perform a search on my website, but I realized one thing. Im using search box generator to customized my search input field. However the problems occur, when I try to apply autocomplete.js on my search input field
Initially, it looks like the one below,
but when I apply the autocomplete feature it will look like this
Code - HTML
<form id="search" novalidate="novalidate" onsubmit="return false;" class="searchbox sbx-google" style="margin-top: 7px;">
<div role="search" class="sbx-google__wrapper">
<input type="search" id="search_input" name="search" placeholder="Search" autocomplete="off" required="required" class="sbx-google__input">
<button type="submit" title="Submit your search query." class="sbx-google__submit">
<svg role="img" aria-label="Search">
<use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#sbx-icon-search-13"></use>
</svg>
</button>
<button type="reset" title="Clear the search query." class="sbx-google__reset">
<svg role="img" aria-label="Reset">
<use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#sbx-icon-clear-3"></use>
</svg>
</button>
</div>
</form>
Code - JAVASCRIPT
autocomplete('#search_input',
{ hint: false }, {
source: autocomplete.sources.hits(index, {hitsPerPage: 5}),
//value to be displayed in input control after user's suggestion selection
displayKey: 'name',
//hash of templates used when rendering dataset
templates: {
//'suggestion' templating function used to render a single suggestion
suggestion: function(suggestion) {
console.log(suggestion)
return '<span>' +
suggestion._highlightResult.title.value + '</span>';
}
}
});
The custom search box is advised by algolia themselves, on the autocomplete documentation. I have no idea on how to solve this problem, seems like the js script overwrite the css styling. This only happen if I passed in the #search_input in the autocomplete function
Here is the js fiddle https://jsfiddle.net/Ldpqhkam/
Algolia autocomplete adds a span around the input and that's what breaks the design. It has inline style changing the display, you can override it to fix the design.
.algolia-autocomplete {
display: inline !important;
}

How to focus a DOM child element from a Meteor event handler

I have an event handler that sets a session variable to change the content within a DOM element -- in this case a table cell.
'dblclick td.itemName': function (evt) {
Session.set("editItemName",true);
evt.currentTarget.children[0].focus();
},
<td class="itemName">
{{#unless editItemName}}
{{name}}
{{else}}
<input class="editItemName" type="text" value="{{name}}" style="width:100px;">
{{/unless}}
</td>
Pretty straight forward...
However evt.currentTarget.children doesnt work. Once the input takes place of the text, I'd like to make it automatically focus... The meteor docs say that this is a DOM object so its weird that the children function doesnt work...
Thanks
Chet
When you double click, and your function runs, you set the session editItemName to true, and then you're trying to give the input-element focus, but the template has not been re-rendered yet, so the input-element hasn't been created (the template will be re-rendered some time after your function returns). In other words: evt.currentTarget.children[0] is not a reference to the input-element.
Possible solution 1
In HTML 5 there's an attribute called autofocus, which you can use (at least I can in Chrome). Just add it to the input-element:
<input autofocus="autofocus" class="editItemName" type="text" value="{{name}}" style="width:100px;">
Possible solution 2
Otherwise you have to focus it with JavaScript when the template been rendered and your input-element exists in it:
Template.yourTemplate.rendered = function(){
var input = this.find('.editItemName')
if(input){
input.focus()
}
}
You are trying to set the focus to a DOM element that has not been rendered yet.
The issue has been bothering me for a while. I have tried to use the autofocus='autofocus' HTML attribute: it has no effect in Firefox, and in Chrome, it seems to only work the first time the element is rendered.
So we need a handler that is called just after the template is rendered, in order to set the focus with javascript. Template.templateName.rendered looks like the way to go, but there is an issue:
What didn't work for me:
<template name="itemName">
<td class="itemName">
{{#unless editItemName}}
{{name}}
{{else}}
<input type="text" value="{{name}}">
{{/unless}}
</td>
</template>
Template.itemName.rendered = function()
{
this.$('input').focus()
}
When doing this, Template.yourTemplate.rendered seems to fire only the first time you click on the item (you get the focus correctly only once).
What worked for me:
<template name="itemName">
<td class="itemName">
{{#unless editItemName}}
{{name}}
{{else}}
{{> itemNameEdit}}
{{/unless}}
</td>
</template>
<template name="itemNameEdit">
<input type="text" value="{{name}}">
</template>
Template.itemNameEdit.rendered = function()
{
this.$('input').focus()
}
Any explanation from a Meteor expert?
As #Chet pointed out, Template.[name].rendered no longer fires whenever a template is updated, but instead, only when the template is first rendered, and only once.
One can pass a callback to Tracker.afterFlush which will fire every time the template is updated.
i.e. all reactive updates are processed
Template.myTemplate.events({
'dblclick td.itemName': function(e, t) {
Session.set("editItemName",true);
Tracker.afterFlush(function() {
this.find('input').focus();
}.bind(t));
}
});

jQuery next() selector when divs are not neighboring

Ive been using the following to change the width of the div.my-div that appears after the one you've clicked:
$(".my-div").click(function () {
$(this).next().css({'width':'500px'});
});
As my divs were neighboring, this worked fine:
<div class="my-div">stuff</div>
<div class="my-div">stuff</div>
<div class="my-div">stuff</div>
However now the structure has changed so they are no longer neighboring:
<div>
<div class="my-div">stuff</div>
</div>
<div>
<div>
<div class="my-div">stuff</div>
</div>
</div>
<div class="my-div">stuff</div>
Whats the simplest way to select the next element of the same class?
Thanks
jQuery will return elements in order of their appearance in the DOM.
As such, you could cache all the .my-div elements, use the index()[docs] method to get the index of the one that received the event, increment it and use the eq()[docs] method to get the next one.
var divs = $(".my-div"); // cache all of them
divs.click(function () {
var idx = divs.index( this ); // get the index in the set of the current one
divs.eq( idx + 1 ).css({'width':'500px'}); // get the one at the next index
});
This saves you from doing a bunch of unnecessary DOM selection and traversing.
Example: http://jsfiddle.net/VrATm/1/
EDIT: Posted wrong example link. Fixed.
You can traverse the tree hierarchy. That is, you can first jump to parent, then to next, then to children, like this:
$(this).parent().next().find(' > div').css({'width':'500px'});

jquery - how to select element and all children, except specific child

I have a .mouseover() event triggered on all elements of class 'node'. It works fine, and is also triggered when user hovers over any child of .node. This works well for me, however, I do not want this event triggered if the user mouse overs a specific child, namely, an image.
Why is the selector $('.node :not(img)') not working?
Oddly enough, it does work when I try it out at http://www.woods.iki.fi/interactive-jquery-tester.html, but not in my actual implementation.
My html:
<div id="container">
<div class="node" id="abc">
<h2>Node Title</h2>
<div class="nodeChildren">
<h3 id="a1">Some text</h3>
<h3 id="a2">Some text</h3>
<h3 id="a3">Some text</h3>
</div>
<img src="diagonal-left.gif" />
</div>
</div>
My jquery:
//start with third tier not visible
$('.nodeChildren').hide();
$('.node :not(img)').mouseover(function(){
$(this).children('div').show();
});
$('.node').mouseout(function() {
$('.nodeChildren').hide();
});
});
My failed attempts
$('.node :not(img)') //no mouseover is triggered
//for the following selectors, the mouseover event is still triggered on img
$('.node').not('img')
$('.node').not($('.node').children('img'))
Thanks for any help :)
The problem is the event is "bubbling" up to the parents which triggers the mouse over. You need to add a mouseover to the img to stop this.
$(".node img").bind("mouseover", function(event) {
event.stopPropagation();
});
in the callback function of bind, you can check the target. in your case, Something like this
$(".node").bind('mouseover',function(e){
if(e.target.nodeName != 'IMG'){
$(this).children('div').show();
}
});