dom - addClass and removeClass in jQuery - not removing class -
i'm trying simple. have clickable div 'hot spot', when click fills screen , displays content. achieved changing class of div, removing 'spot' , adding 'grown' , there's little css animation make grow. works fine.
the problem is, within div there close_button, @ moment text. want switch classes - i.e. remove grown , readd spot. doesn't when clicked. believe it's element not having classes when dom loads, i'm new jquery , don't know how work around this.
i think there's more sensible way of doing it, point me in right direction? i'd grateful. i've tried using toggleclass instead no avail.
$( document ).ready(function() { $(".clickable").click(function() { $(this).addclass("grown"); $(this).removeclass("spot"); }); $(".close_button").click(function() { alert (this); $("#spot1").removeclass("grown"); $("#spot1").addclass("spot"); }); });
update:
i using code now,
$( document ).ready(function() { $(document).on("click", ".close_button", function () { alert ("oi"); $("#spot1").addclass("spot"); $("#spot1").removeclass("grown"); }); $(document).on("click", ".clickable", function () { if ($(this).hasclass("spot")){ $(this).addclass("grown"); $(this).removeclass("spot"); } }); });
strangely close_button function still won't add 'spot' or remove 'grown' though add other classes , remove other classes... added if clause because thought perhaps both function being triggered @ same time, undoing each other, seems make no difference
what happens close button placed inside .clickable
div, click event triggered in both elements.
the event bubbling make click event propagate child nodes parents. .close_button
callback executed first, , when .clickable
reached, toggle classes again. run fast can't notice 2 events happened.
/ \ --------------------| |----------------- | .clickable | | | | ----------------| |----------- | | | .close_button | | | | | ------------------------------ | | event bubbling | ----------------------------------------
to prevent event reaching .clickable
, need add event parameter callback function , call stoppropagation
method on it.
$(".close_button").click(function (e) { $("#spot1").addclass("spot"); $("#spot1").removeclass("grown"); e.stoppropagation(); });
fiddle: http://jsfiddle.net/u4gck/1/
more info event order in general: http://www.quirksmode.org/js/events_order.html (that's picked pretty ascii art =])
Comments
Post a Comment