简体   繁体   中英

Reverse onClick Event onClick

Does anyone know how to assign an onClick to an object that performs one action, then when the user clicks on the same object, the action is reversed?

$('#image').click(function() {
    $('#foo').css({
        'background-color': 'red',
        'color': 'white',
        'font-size': '44px'
    });
});

So clicking on #image will either add the changes to #foo or reverse changes.

Fiddle: http://jsfiddle.net/Sx5yH/804/

Any suggestions?

Don't manipulate with inline styles directly, this is not very flexible approach. Instead you want to toggle class that holds necessary styles:

$('#image').click(function() {
    $('#foo').toggleClass('active');
});

where the class active is defined like this:

#foo.active {
    background-color: red;
    color: white;
    font-size: 44px;
}

Demo: http://jsfiddle.net/Sx5yH/812/

Specifically in your case - it is better to assign a class to the object. Then you can use the jquery toggle functionality to add/remove the style.

CSS

#image.selected {
       background-color: red;
       color: white;
       font-size: 44px;
}

JavaScript

$('#image').click(function() {
    $('#image').toggleClass("selected");
});

http://jsfiddle.net/gb0udnft/1/

You can use a boolean value to determine whether or not it's been clicked, then use a ternary statement to do whatever depending if it's true or false.

(boolean) ? true : false;

You could also use the innate JQuery toggle() function

http://jsfiddle.net/gb0udnft/2/

    $('#image').toggle(function() {
    // do whatever 
       }
      , function() {
       // do whatever
});

or use a css class back and forth by using .toggleClass(), .addClass(), or .removeClass()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM