Reputation: 43
I want to create a button that changes its content when being clicked, but also when i click again the content must return to its initial look. I've managed to create a jQuery code, which changes the content, but need help for the part with the second click. My aim is this button to have two conditions and depending on the active one when being clicked to switch to the second condition.
$("#changeArrow").click(function(){
var textShowing = true;
if (textShowing == true){
$("#changeArrow").html(function(){
return "This is some text! ⊗";
textShowing = false;
});
}
else {
$("#changeArrow").html(function(){
return "This is some text! ⊕";
textShowing = true;
});
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="changeArrow">This is some text! ⊕</button>
Upvotes: 0
Views: 144
Reputation: 337656
One way to do this is by providing a function to html()
which checks what the current content is and returns the new content based on that, something like this:
$("#changeArrow").click(function() {
$(this).html((i, h) => h == 'This is some text! ⊕' ? 'This is some text! ×' : 'This is some text! ⊕');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="changeArrow">This is some text! ⊕</button>
However, as all you're doing is changing the icon then this could be made even simple if you add the icon using CSS. Then you can simply toggle a class on each click:
$("#changeArrow").click(function() {
$(this).toggleClass('close');
});
#changeArrow:after {
content: '⊕';
margin: 0 -1px 0 4px;
display: inline-block;
}
#changeArrow.close:after {
content: '×';
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="changeArrow">This is some text!</button>
Upvotes: 2
Reputation: 68923
You should declare the flag variable (textShowing) outside the click event handler function. Also, you can use this
keyword to refer the clicked element:
var textShowing = true;
$("#changeArrow").click(function(){
if (textShowing == true){
$(this).html("This is some text! ⊗");
textShowing = false;
} else {
$(this).html("This is some text! ⊕");
textShowing = true;
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="changeArrow">This is some text! ⊕</button>
Upvotes: 1