Reputation: 633
I am trying to make a button that will make text disappear when clicked, accompanied by an alert, and then make it reappear accompanied by a different alert when clicked again. The code I have so far is:
$(".great-grandma-button").click(function(){
$("#great-grandma").find("h1").toggle();
alert("Grandma's Gone!");
});
so making the text disappear and reappear is easy enough, the initial alert is simple as well so really I just need to know how to have a different alert associated with the second click.
Upvotes: 0
Views: 67
Reputation: 1189
You can either use one of jQuery functions or selectors to check whether the content is currently visible (i.e. $('h1').is(":visible")
or just use this selector $('h1:visible')
) or you can make a use of the variable as follows:
var isVisible = true;
$(".great-grandma-button").click(function(){
$("#great-grandma").find("h1").toggle();
if (isVisible) {
alert("Grandma's Gone!");
} else {
alert("Grandma's Back!");
}
isVisible = !isVisible;
});
Upvotes: 0
Reputation: 8370
Since the .toggle()
function is already modifying the element's visiblity, you can use the .is(':visible')
function on said element for something like this:
$(".great-grandma-button").on('click', function(e) {
var h1 = $("#great-grandma").find("h1");
h1.toggle();
if (h1.is(':visible')) {
alert("The thing is visible.");
} else {
alert("The thing is NOT visible");
}
});
Upvotes: 2
Reputation: 818
You can set a variable, or add a class to one of the elements, depending on how many you have it will change how easy each solution is.
var grandmaVisable = true;
$(".great-grandma-button").click(function(){
$("#great-grandma").find("h1").toggle();
if (grandmaVisable == true) {
grandmaVisable = false;
alert("Grandma's Gone!");
} else {
grandmaVisable = true;
alert("Grandma's Back!");
}
});
A better way though would be to just use jQuery's .toggleClass()
toggle a CSS class onto the hidden one. The CSS for that class could then mark it as hidden.
If you need to do other things when the class is hidden / shown then you could use .hasClass()
to see if the flag for hidden is present or not.
https://api.jquery.com/toggleClass/
https://api.jquery.com/hasClass/
Upvotes: 0