jQuery Click event on object added with JavaScript not working - javascript

I'm working on a quiz for school but I've bumped into a problem. I got a JavaScript library for custom radio buttons (CUSTOM FORM ELEMENTS by Ryan Fait if it's helping). The script hides the input buttons and adds custom styled spans instead.
Desired behaviour, when I click one a span (added with JavaScript) I want to remove disabled attribute from my "Next Question"-button which when pressed takes you to the next question. I don't want users to accidentally proceed to the next question, without choosing an answer.
The problem is when I press the added spans nothing happens, but when I press another identical span which I have added in the HTML it works just as intended.
The span got the class radio, which I'm doing a lookup on with jQuery.
Short: Can't get jQuery .click() functions to work with spans added using JavaScript earlier in the document.

You are looking for jQuery's live() function. You would do something like:
$(".radio").live("click", function() {
// Enable the button here
});
Your other option would be to use the new delegate() function if you have jQuery 1.4.2 included on your page. Similar syntax, however, it only scans within the element it's called on for child elements of the kind you want to bind an eventListener to and I believe it has much less of a performance impact on large pages. (Not applicable in your case, but it's always good to practice with the best tools.)
$("element_containing_radio_buttons").delegate(".radio" "click", function() {
// Enable the button here
});

Related

JQuery - best way to swap in and out parts of the UI

What's the best way to "preserve" and "re-display" portions of an html page, along with jquery event handlers you've set up?
More detail:
I'm writing a "one-page javascript application" that lets users perform two different calculations. The user selects which calculation they want by clicking a radio button.
When they click radio button A, a big part of the UI needs to get displayed with appropriate html controls (and jquery event handlers) that allow the user to enter the parameters for calculation A.
Likewise, if the user clicks radio button B, that section of the page needs instead to show all the controls (and its associated jquery event handlers) that allow the user to enter the parameters for calculation B.
My question is how to best handle the swapping of calculation A and B's html controls and their associated jquery event handlers?
I had thought about just using jquery's .html() to get and set the parameter section part of the page, but I'm thinking that will not preserve any event handlers that I'd set up for those controls. Is that right? In that case, I'd need to either re-wire up the event handlers as the user switches between calculations or do something else.
(In essence I think what I want to do is to be able to preserve a chunk of the dom (which hopefully includes jquery event handlers) but I don't write a ton of jquery and am I'm not sure how to approach that... I'm wondering if I could get the whole parameter section of a page represented as a jquery node, and save that off (to a js variable) and restore it, as needed, if that would do the trick??
Thanks for any ideas!
Michael
Honestly, usually it's easier just to hide()/ show() elements rather than removing them/ re-adding them.
Add a calculation-1 class to elements you want to be visible for the first calculation, and calculation-2 for the second calculation elements. This will let you get a jQuery variable of all calculation 1 and 2 elements via $('.calculation-1') and $('.calculation-2).
You can then add an event handler for the radio's that hide() and show() the elements accordingly.
If you use html(), you'll lose events bound to the elements children. Unless you attach your handlers to an ancestor which you don't remove.
You can also use detach(), which will remove the elements from the DOM, but persist the event handlers you added. However, if your elements are dotted all over the DOM, it's hard to track their origional position, and TBH is more effort than it's worth.

Toggle Open/Close JS function

I've never posted here before, and I'm hoping you can help me. I have a js function that on click will toggle display and hiding a paragraph. However, I need to nest them upon one another. In other words:
1) Some text here //Click to open
2)This text opens upon click //Click to open
3)This text opens upon click.
They way I have it written now, clicking 1 opens 2 up, but clicking 2 closes everything. I'm just learning JS now, so I'm now the best with it, so I'm hoping the pros here can help me. Here's what my function looks like now http://pastebin.com/ZUzp1pUJ Anyone got any ideas?
I noticed you included jQuery in your HTML but you're not using it anywhere, I'll assume you're new to jQuery and willing to use it.
Here's what you do.
First you should read up on the jQuery Reference. It is extremely useful.
The things you need to give extra attention to are these:
jQuery Selectors - use $('.myClass') instead of getElementsByClassName
jQuery Toggle - or any of it's companions (slideToggle, fadeToggle) to do exactly what you asked for.
and as to your question - stopPropagation - which allows you to trigger only the toggle that you clicked and stop the event from bubbling up through the dom. (and not to trigger it's parents.)
These three combined should do the work. Good luck.

How to make all buttons(even dynamically created) in an application follow jquery button widget without calling .button() multiple times

I am new to stack overflow and this is my first question. Pardon me for any mistakes.
This question is more generic but i tried to search for an answer but could not find it.
Say i have a page and i am using jquery ui button() widget for all the button. What happens is i have a specific class defined for all the buttons on my page. So i can just specify $('.myButtonClass').button(); but whenever i render partial views which has button again i have to do the same thing in the partial views. Is there any way i can globally specify a transition for button or any element for that matter.
Here is a sample Fiddle which adds buttons on click. But the added buttons are not transitions as button widgets(I do not want to use clone).
http://jsfiddle.net/wjxn8/
$('.clsTest').button().click(function(){
$(this).after('<input type="button" value="Added" class="clsTest"/>');
});
Is this possible without:-
1) Adding the css classes for a button widget manually for all the buttons created.
2) Tracking DOM Changes using Javascript and perform transitions for all the button elements.
Thanks for your help!!!
Since you were looking for something else, why not trigger a custom event when you load partials or whatever:
$('.clsTest').button().click(function(){
$(this).after('<input type="button" value="Added" class="clsTest"/>').trigger('addButtonUI');
});
$(document).bind('addButtonUI',function(){
$('.clsTest').button();
});
http://jsfiddle.net/wJXN8/3/
If you trigger your event and have the document listening for it, then you can do whatever you would like. I could have put in there the ability to add more buttons as well, but this should get the point across.
What you are asking for, some event when a button is added.... you would need to come up with that yourself and trigger it when a button is added. There is this: How to detect new element creation in jQuery? which talks about a specific event that is triggered when new elements are added to the DOM. Haven't tested it, and it looks like it may not work on IE.
I'm not a huge fan of this, but you could poll for new buttons. Check out my fork of your fiddle (that sounds funny):
http://jsfiddle.net/lbstr/Hq97H/
Using your example, this would look like:
setInterval(function(){
$('.clsTest').not('.ui-button').button();
}, 1000);
As I said, I'm not a huge fan of this. I understand the desire for something like $.live here, but I still think its better to initialize your new content when you add it. If you are making an ajax call for new content, just initialize it when you add it to the DOM.
My silly polling code and $.live (which is now deprecated) might be convenient, but they perform terribly. Just my two cents. You know your code better than I do!

Events not always firing

I'm not really sure how to go with this, but here goes:
I have form elements that trigger a function (mainly for validation purposes). This triggers on click, on change etc. These are written with vanilla JavaScript.
If it's a straight-forward HTML element then everything works fine. E.g. a element fires on change.
However, if I use a jQuery script (e.g. a jQuery colour selector), then although that jQuery script populates an field, the validation script doesn't fire.
This I suppose is obvious as you don't click, blur, change it, it's just the jQuery script changing it.
Of course I could change the JavaScript in the colour selector jQuery script so it also fires the validation script, but there must be a better way where as well as on click, on change, on blur etc. I can also activate the function when it picks up that another script is changing it. I need this for various occasions and scripts.
Another example is a rating script (rate out of 5). It uses radio buttons as a non-jQuery fallback and the jQuery script just hides those radios (with CSS), displays the star images and then changes the radios when the user interacts with the star images. That way the server handles a form submit the same way regardless of the availability of jQuery. However, the validation script doesn't fire.
Any ideas?
Apparently the elements are being inserted on the dom after the javascript run.
try using $.live() instead of $.blur()
so even if this script elements are inserted after the page rendered, events will be bound to em.
http://api.jquery.com/live/

Binding JQuery events

JQuery events are annoying me. The thing is that I very often use
javascript (after ajax requests, etc.) to draw up new elements
(buttons, divs, etc.). I've got a list of elements
which you can press on an edit button so you can manipulate the one
linked to the selected edit button.
Now if someone submits a form to make a new element like the ones who
existed before, and I submit it with ajax and then I append or prepend
the new element into the list. After that the new edit button for the
new element isn't linked to JQuery's event system since the DOM hasn't
been reloaded after the edit button was made. If I call the same
javascript file with the events in it, then the edit button works but
then when people click other edit buttons the event happens twice for
them since they're bound twice. I've also used .bind() but that only
binds (I think) the same event twice as before. I don't remember at
the moment how I tested it. I haven't tested .one() but I would rather
not use it since some events must be called more than once.
I just wanted to ask you guys what approach you use when dealing with
the events?
P.S. I'm binding the JQuery event to the class attribute that all the elements have. If I was going to bind this to each element based on ID, then this wouldn't be a problem because then I would just use .bind(). By writing this I suddenly though of using .unbind() and then .bind() to link the elements to the events system. What do you think of that? Would you do it in another way?
Thanks in advance.
Kristinn.
You're looking to use $.fn.live:
$('a').live('click', function(e) {
e.preventDefault();
alert('im attached even if the DOM has been updated!');
});
http://docs.jquery.com/Events/live
Your question is a bit general, but I have a feeling that what you're looking for is jquery live
http://www.thewebsqueeze.com/tips-and-tricks/tip-for-jquery-live-event.html
http://simpable.com/code/jquery-live-events/
http://www.thefutureoftheweb.com/blog/jquery-live-events
http://kylefox.ca/blog/2009/feb/09/live-event-binding-jquery-13/

Categories