Shameer
Shameer

Reputation: 233

jQuery toggle() function not working

This question may be asked before. But I cant find the error. Here this is from the video tutorial of new boston.

$(document).ready(function(){
$('#btn').toggle(function(){
    $('#msg').html('yes');
},function(){
    $('#msg').html('No');
});
});

The video showing that when click first the div text is yes and next time it show no But when I try, when the page loads, the button fadeout and div show no. Why? There may be other methods to achieve this functionality. But why this dont work. He showing the syntax of toggle as

$('#btn').toggle(function(){code},function{code});

Upvotes: 0

Views: 14366

Answers (1)

http://api.jquery.com/category/deprecated/

Note: This method signature was deprecated in jQuery 1.8 and removed in jQuery 1.9. jQuery also provides an animation method named .toggle() that toggles the visibility of elements. Whether the animation or the event method is fired depends on the set of arguments passed.

http://api.jquery.com/toggle-event/

Updated after OP's comment

DEMO

if you want to make this code work in any version of jQuery

$(document).ready(function () {
    var arr = ['yes', 'no'],
        i = 0;
    $('#btn').click(function () {
        $('#msg').html(arr[i++ % 2]);
    });
});

DEMO

if you want to make use of toggle-event like functionality in future

use .one()

$(document).ready(function () {
    function handle1() {
        $('#msg').html('yes');
        $('#btn').one('click', handle2);
    }

    function handle2() {
        $('#msg').html('no');
        $('#btn').one('click', handle1);
    }
    $('#btn').one('click', handle1);
});

or

Toggle was removed in version 1.9, so you cannot use it - if you want this logic can be manually implemented or you can make use of the migration plugin

to include the migration plugin, after the inclusion of jQuery library add

<script src="http://code.jquery.com/jquery-migrate-1.2.1.js"></script>

Upvotes: 12

Related Questions