I have the following problem: in order to mark an element during different situation I want to add a class to the element:
jQuery('#menu-item-41 a').addClass('newsbox-closed1');
Later I want to do some funny staff when the element with this class is clicked – so far it works fine:
jQuery('.newsbox-closed1').click(function(){
jQuery('#newsbox').css('display', 'block');
jQuery(this).css('background-color', '#FF33AB').removeClass('newsbox-closed1').addClass('news-open');
});
Until now everything is just fine. The element gets the class “news-open” andf the newsbox appears. But then the following does not work anymore:
jQuery('.news-open').click(function(){
alert('JUCVJU');
jQuery(this).removeClass('news-open').addClass('newsbox-closed2');
jQuery('#newsbox').css('display', 'none');
});
Idea: when someone clicks on the same link again, the newsbox should disappear and the link gets a new class. This does not work – the class “new-open” is not removed, the alertbox is not shown, nothing.
Additionally the following work half the way – it is a close button on the newsbox:
jQuery('#close').click(function(){
jQuery('#newsbox').css('display', 'none');
jQuery('.news-open').removeClass('news-offen').addClass('newsbox-closed2')
});
The element with id “newsbox” disappears but the second part has no effect. The class remains of this element. I get no error messages, nothing… does anyone has an idea what can cause this?
Best,
Tobias
You are adding class at runtime. Change
to
Above is for JQuery >=1.7
For JQuery <1.7, use
live and on in JQuery work for elements created at runtime too.