简体   繁体   中英

Create Second Click Event Javascript Only

I need to have an image change opacity when I click a button and then change back when I click the button again. I can only use Javascript. I've set up 2 if/else statements and when I click the button the first time the event happens but I can't get a second event to happen. I'm very new to javascript.

var img = document.querySelector('#img');
var button1 = document.querySelector('#button1');
var bool = new Boolean();


if (chrome.style.opacity = "1.0"){
    bool = true;
    }
else if (chrome.style.opacity = "0.5"){
    bool = false;
    }

if (bool){
    button1.addEventListener('click', function() {
    chrome.style.opacity = "0.5";
    });
    }
else{
    button1.addEventListener('click', function() {
    chrome.style.opacity = "1.0";
    });
}

Use one click event and put the if/else statement inside it.

button1.addEventListener('click', function() {
     if (chrome.style.opacity = "1.0"){
          chrome.style.opacity = "0.5" 
    }else{
          chrome.style.opacity = "1.0"
    }
 });

Try this

html

<button id="button1">hi</button>

css

button {
    opacity: 0.5;
}

js

button1.addEventListener('click', function() {   
    this.style.opacity = (this.style.opacity == 1.0) ? 0.5 : 1.0;            
});

i suppose your js would actually be this ..just adapt it

button1.addEventListener('click', function() {   
    chrome.style.opacity = (chrome.style.opacity == 1.0) ? 0.5 : 1.0;            
});

http://jsfiddle.net/Q4C6g/

Just a comment on your code:

> var bool = new Boolean();

You really don't want to do that. Boolean objects exist to support boolean primitives, not to be used on their own. Also, don't assign a value until you have to. Initialising variables to a temporary value is pointless, it certainly doesn't "type" the variable.

ECMAScript variables don't have a type, their values do. So when you later do:

> bool = true;

bool no longer references the object assigned previously, it now has a value of true .

The use of bool can be completely avoid here anyway, see other answers.

Oh, and why you should avoid Boolean objects:

// Create a Boolean object with a value of false
var foo = new Boolean(false); 

// Evaluate in expression that will call internal getValue method
alert( foo );  // false

// Evaluate in expression that will do Type conversion
alert( !foo ); // false

Ooops! Just to be sure:

alert( foo == !foo  ); // true!!
alert( foo == !!foo ); // false

So stay away from Boolean objects! Even if you use this behaviour to your advantage, readability and maintenance will suffer.

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