Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
45
rated 0 times [  51] [ 6]  / answers: 1 / hits: 30358  / 11 Years ago, tue, march 12, 2013, 12:00:00

Let me define the problem a little bit more:



i have



    <div class=contact>
<div id=form></div>
<div id=icon></div>
</div>


i want onclick on #icon, to change the class of .contact to .contactexpand( or just append it).



Then i want that the on body click to change the class back, but of course that shouldnt happen when clicking on the new class .contactexpand, and if possible that clicking on icon again changes the class back again.



I tried numerous examples and combinations but just couldn't get the right result and behavior.


More From » jquery

 Answers
5

Check this: Working example



Let's go step by step




I want onclick on #icon, to change the class of .contact to .contactexpand( or just append it). […] and if possible that clicking on icon again changes the class back again.




You want to use the toggleClass() method to achieve this. Simply:



$('#icon').on('click', function(e){

$(this).parent()
.toggleClass('contact')
.toggleClass('contactexpand');

});



Then i want that the on body click to change the class back




You will have to make sure that body removes contactexpand class and adds contact. At this point I would just give the container element an id (or class if you prefer), just to make things simpler. Then what you do is pretty simple:



$('body').on('click', function(e){

$('#thisdiv')
.removeClass('contactexpand')
.addClass('contact');

});



but of course that shouldnt happen when clicking on the new class .contactexpand.




This is the step that the other answers missed, I think. Since everywhere you click, you also click on the body element, you will always trigger the click event on the body, hence removing the contactexpand class and adding the contact one.



Enter event.stopPropagation(). This method will make sure that the events doesn't bubble up the DOM, and will not trigger the body click.



$('#thisdiv').on('click', function(e){

e.stopPropagation();

});


Working example


[#79646] Monday, March 11, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kieraelsies

Total Points: 718
Total Questions: 103
Total Answers: 104

Location: England
Member since Sun, May 21, 2023
1 Year ago
kieraelsies questions
Tue, Aug 3, 21, 00:00, 3 Years ago
Tue, Feb 23, 21, 00:00, 3 Years ago
Thu, Nov 12, 20, 00:00, 4 Years ago
Wed, Sep 9, 20, 00:00, 4 Years ago
Mon, Sep 16, 19, 00:00, 5 Years ago
;