Reputation: 1890
Based on a question answered earlier on SO, I've make this script which adds a CSS class to an element onClick. The problem is that it only works one time. How do I reset the function?
This is the jQuery code:
jQuery(function() {
jQuery('.close-button').click(function(){
jQuery(".content-display").addClass("cover");
jQuery(".close-button").addClass("cover");
});
jQuery('.project').click(function(){
jQuery('.content-display').addClass("uncover");
jQuery('.close-button').addClass("uncover");
});
});
And a fiddle with everything.
Upvotes: 0
Views: 1229
Reputation: 2142
You need to remove alternative class on action. After you press both close and project in your current code, you have both cover and uncover classes
jQuery(function() {
jQuery('.close-button').click(function(){
jQuery(".content-display").addClass("cover").removeClass("uncover");
jQuery(".close-button").addClass("cover").removeClass("uncover");
});
jQuery('.project').click(function(){
jQuery('.content-display').addClass("uncover").removeClass("cover");
jQuery('.close-button').addClass("uncover").removeClass("cover");
});
});
For this particular case usage of uncover class seems to be unnecessary, I vote for simple removeClass solution (@Stuart Feldt)
Upvotes: 2
Reputation: 368
If you are just wanting to hide and show the div, you can try:
jQuery(function() {
jQuery('.close-button').on('click', function(){
jQuery(".content-display").addClass("cover");
jQuery(".close-button").addClass("cover");
});
jQuery('.project').on('click', function(){
jQuery(".content-display").removeClass("cover");
jQuery(".close-button").removeClass("cover");
});
});
Upvotes: 1
Reputation: 91299
Use .toggleClass()
instead:
jQuery('.project').click(function(){
jQuery('.content-display').toggleClass("cover");
jQuery('.close-button').toggleClass("cover");
});
});
This way, if the class is already there, it will be removed; otherwise, it will be added. Also, you should toggle the cover
class, since the div
s are initially visible.
DEMO.
Upvotes: 4