Lewis Day Lewis Day - 1 month ago 10
jQuery Question

Onclick change text in a link not working?

What I'm trying to achieve on on the link click the text change to the second span; however this is not working.

Script

var reload = false;
$('#change').click(function() {
reload = !reload;
$('#change').click(function() {
$('span',this).toggle();
});
});


HTML

<li role="presentation" class="pull-right">
<a href="#" id="change">
<span>text 1</span><span style="display:none">text 2</span>
</a>
</li>

Answer

You've complicated it with a flag and nested event handlers, just remove that and it works

$('#change').click(function() {
    $('span', this).toggle();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
    <li role="presentation" class="pull-right">
        <a href="#" id="change">
            <span>text 1</span><span style="display:none">text 2</span>
        </a>
    </li>
</ul>

When you nest event handlers inside each other, you keep binding new event handlers on each click, and they keep counteracting each other, and it won't work as expected.
This is why you should generally never nest event handlers.