I have created some divs programmatically with jQuery and I would like to apply the same functionality to all divs.
I have created an example to jsfiddle. Check it here
As you can see in the example the first <div class="autosize"> behaves really well but the second <div class="autosize_2"> does not have any functionality except from the click (actually I am not sure why click works).
Can someone help me or give me an example on how to achieve the desired functionality?
Thanks
It seems to work fine if you just add #pointer_div_2 after every #pointer_div separated by a comma.
$('#pointer_div, #pointer_div_2').on ... etc.
Example: http://jsfiddle.net/wm3y5/13/
Basically, you are just targeting multiple selectors using the comma
Read more: http://api.jquery.com/multiple-selector/
You could use class="autosize" on all of them. If you actually need unique id's for each you should use id="autosize", id="autosize_2",etc in addition to the class.
Or you could use multiple classes on each: class="autosize autosize_1", class="autosize autosize_2", etc.
You can use
$(document).on('click',selector,handler)
in order to attach an handler to all elements matching selector now and in the future.
Related
I have multiple divs with ids like course1_popup, course2_popup, course3_popup. I want to make a function something like
$('#course*_popup').hide();
so that all course*_popup divs should hide but this is not working. Any Ideas?
Use the combination of attribute starts with and ends with selectors.
$('[id^="course"][id$="_popup"]').hide();
FYI : It would be much better to use a common class for the group of elements for such things.
Easiest way: Give all the same class like course_popup and then:
$('.course_popup').hide()
Other solution was postet a sec ago ;)
I'm just wondering how I can select elements in jQuery dynamically, for example here is a selector of mine:
$("#video_background_video_0, #video_background_video_1, #video_background_video_2, #video_background_video_3, #video_background_video_4").remove();
As you can see this isn't the best example of DRY programming, I'd like to create a selector that selects all elements that begin with #video_background_video_. I basically just want to select the above elements in the cleanest way, I was wondering if there is a way that I can dynamically select these elements with some sort of count instead of placing all of my selectors like so, it just looks very messy and I'm wondering if there is a better way to do this when it comes to elements with a numeric ending?
As jQuery uses a CSS selector syntax I am unsure how I can do this.
Thanks, Nick
You can use start-with selectors:
$('[id^="video_background_video"]').remove();
There are other attribute selectors you might be interested here.
Try to use attribute starts with selector,
$("[id^='video_background_video'")
Also make sure that, this selector is not a native css based one. It will fetch the elements after executing regular expressions internally. So it would be better to use it in a minimum level. Its Better to set a common class to those elements and use class selector instead.
I have a list of questions and answers grouped in different divs. I would like to collapse them when a click event is fired that is placed on the question. I have read the examples from the Twitter Bootstrap page but I would like to tricker the event with Javascript and not with data-attributes. With data-attributes every question needs a unique id and this will hard to maintain in the future. I want to trigger the class ".collapse"
Code: http://codepen.io/anon/pen/grdnA
Try this example. You can always modify it according to the element being watched for click and the element to toggle.
jsFiddle
You can use slideToggle() instead of toggle() to get the collapsing effect.
Regards
Something like this? Remember to include jQuery library
$('[data-toggle="collapse"]').on('click', function () {
$(this).closest('div.panel').find('.collapse').toggle('')
});
DEMO
I am having a devil of a time getting two selectors to work together as well as do when I declared seperate.
My issue:
I want to close a menu when I move to any input OR anchor tag that is NOT contained with a certain element. When I explicitly code for both input and anchor, I get the behavior I need - BUT when I try to condense my code and combine them, it behaves weirdly and does not work as intended.
So, basically when a user focus's in an input field or anchor that is NOT a child of my selector I want to close a menu. When I use two sperate handlers, it works. I want to combine them.
I am trying to shorten this....
jQuery('#hdr input:not(#opt *)')
.focusin(function(event){
setTimeout(function(){
jQuery("#opt").hide()
},100);
});
jQuery('#hdr a:not(#opt *)')
.focusin(function(event){
setTimeout(function(){
jQuery("#opt").hide();
},100);
});
I've tried all of this into one line, to no avail:
jQuery('#hdr a input:not(#opt *)')
jQuery('#hdr a, #hdr input:not(#opt *)') <-- I expect this to work, but doesn't.
jQuery('#hdr a,input:not(#opt *)')
jQuery('#hdr *:not(#opt *)')
It seems to only work when I do a single arg like: #hdr a , or #hdr input BUT when I try to combine them, no luck. I've searched high and low but no luck.
You can use the not method:
$('#hdr').find('a,input').not('#opt *')
Sometimes it's just better and more readable to use the methods instead of a huge selector string.
All the elements are child of #opt and not selector ensure that #opt which is parent and all the elements or nodes in it are prevented from event handler. Like this in Fiddle:
Working Fiddle
Also The Method of #elclanrs works.
$("#hdr a:not(#opt), #hdr input:not(#opt)")
I write a lot of dynamically generated content (developing under PHP) and I use jQuery to add extra flexibility and functionality to my projects.
Thing is that it's rather hard to add JavaScript in an unobtrusive manner. Here's an example:
You have to generate a random number of div elements each with different functionality triggered onClick. I can use the onclick attribute on my div elements to call a JS function with a parameter but that is just a bad solution. Also I could generate some jQuery code along with each div in my PHP for loop, but then again this won't be entirely unobtrusive.
So what's the solution in situations like this?
You need to add something to the divs that defines what type of behaviour they have, then use jQuery to select those divs and add the behaviour. One option is to use the class attribute, although arguably this should be used for presentation rather than behaviour. An alternative would be the rel attribute, but I usually find that you also want to specify different CSS for each behaviour, so class is probably ok in this instance.
So for instance, lets assume you want odd and even behaviour:
<div class="odd">...</div>
<div class="even">...</div>
<div class="odd">...</div>
<div class="even">...</div>
Then in jQuery:
$(document).load(function() {
$('.odd').click(function(el) {
// do stuff
});
$('.even').click(function(el) {
// dostuff
});
});
jQuery has a very powerful selector engine that can find based on any CSS based selector, and also support some XPath and its own selectors. Get to know them! http://docs.jquery.com/Selectors
I would recommend that you use this thing called "Event delegation". This is how it works.
So, if you want to update an area, say a div, and you want to handle events unobtrusively, you attach an event handler to the div itself. Use any framework you prefer to do this. The event attachment can happen at any time, regardless of if you've updated the div or not.
The event handler attached to this div will receive the event object as one of it's arguments. Using this event object, you can then figure which element triggered the event. You could update the div any number of times: events generated by the children of the div will bubble up to the div where you can catch and handle them.
This also turns out to be a huge performance optimization if you are thinking about attaching multiple handlers to many elements inside the div.
I would recommend disregarding the W3C standards and writing out HTML-properties on the elements that need handlers attached to them:
Note: this will not break the rendering of the page!
<ul>
<li handler="doAlertOne"></li>
<li handler="doAlertTwo"></li>
<li handler="doAlertThree"></li>
</ul>
Declare a few functions:
function doAlertOne() { }
function doAlertTwo() { }
function doAlertThree() { }
And then using jQuery like so:
$("ul li").each(function ()
{
switch($(this).attr("handler"))
{
case "doAlertOne":
doAlertOne();
break;
case ... etc.
}
});
Be pragmatic.
It's a bit hard to tell from your question, but perhaps you can use different jQuery selectors to set up different click behaviours? For example, say you have the following:
<div class="section-1">
<div></div>
</div>
<div class="section-2">
<div></div>
</div>
Perhaps you could do the following in jQuery:
$('.section-1 div').onclick(...one set of functionality...);
$('.section-2 div').onclick(...another set of functionality...);
Basically, decide based on context what needs to happen. You could also select all of the divs and test for some parent or child element to determine what functionality they get.
I'd have to know more about the specifics of your situation to give more focused advice, but maybe this will get you started.
I haven't don't really know about JQuery, but I do know that the DOJO toolkit does make highly unobtrusive Javascript possible.
Take a look at the example here: http://dojocampus.org/explorer/#Dojo_Query_Adding%20Events
The demo dynamically adds events to a purely html table based on classes.
Another example is the behaviour features, described here:http://dojocampus.org/content/2008/03/26/cleaning-your-markup-with-dojobehavior/