afro360
afro360

Reputation: 620

jQuery Img toggle Ajax post

I have two images, when I click on green.png it changes to red.png. But when I load the page and its already set as red.png I need to click the img twice before it changes.I would like to only click once.

    $(".page-state").toggle(function(event){
    this.src = "images/red.png";

        var id = event.target.id; //the Div ID variable         
        var dataString = 'page='+ id + '&view=off';         

        $.ajax({
            type: "POST",
            url: "pageState.php",
            data: dataString,
            cache: false,
        });
        $('#mainFrame')
        .attr('src', $('iframe')
        .attr('src'))

    }, function(event) { 
        this.src = "images/green.png";

        var id = event.target.id; //the Div ID variable         
        var dataString = 'page='+ id + '&view=on';          

        $.ajax({
            type: "POST",
            url: "pageState.php",
            data: dataString,
            cache: false,
        });
        $('#mainFrame')
        .attr('src', $('iframe')
        .attr('src'))
    });

How can I improve this?

Upvotes: 1

Views: 171

Answers (1)

Talha Akbar
Talha Akbar

Reputation: 10040

jQuery:

$(".page-state").click( function() {
    var s = $(this).attr("class").split(" ");
    if(s[1] == 'red') {
        this.src = 'green.png';
        $(this).removeClass('red').addClass('green');
        // more code for green
    }
    else {
        this.src = 'red.png';
        $(this).removeClass('green').addClass('red');
        // more code for red image
    }
});

HTML:

<img class="page-state red" src="red.png" />

As you can see that .page-state has class which indicates that what by default, it consists red or blue.

Upvotes: 1

Related Questions