H0ndman2
H0ndman2

Reputation: 41

Trying to create a button with 2 states

So I'm trying to create a button with 2 states that it can be switched between by clicking on it. Something like the like button facebook has. It switches between the grey not-liked stage and the blue liked stage. I'm trying to do this with an icon I created.

html (using 6 of them in my code)

<img id="list" src="img/listwhite.svg">

css

section article div img {
    height: 1em;
    width: 1em;
    opacity: 0.2; 
}

#list {
    transition: all 300ms ease-in-out;
}

#listselected {
    transition: all 200ms ease-in-out;
    opacity: 0.8;
}

javascript

function listClick (){
    document.getElementById('list').id = 'listselected';
}
document.getElementById("list").addEventListener("click", listClick);


function listunClick (){
    document.getElementById('listselected').id = 'list';
}
document.getElementById("listselected").addEventListener("click", listunClick);

Right now using this code, the first part works, but during the second part something goes wrong. Instead of changing the state of this first icon, the state of another #list on my site will change to #listselected. I don't know what to change right now and I was hoping you guys could help me out.

Thanks

Upvotes: 2

Views: 1358

Answers (2)

Kevin Jantzer
Kevin Jantzer

Reputation: 9461

You need quite a few changes, but here's a basic working example.

They key is you dont want to change the ID of your element, rather apply and remove a class .selected

#list {
  height: 3em;
  width: auto;
  opacity: 0.2;
}

#list {
  transition: all 300ms ease-in-out;
}

#list.selected {
  transition: all 200ms ease-in-out;
  opacity: 0.8;
}
<img id="list" onclick="this.classList.toggle('selected')" src="http://mygimptutorial.com/images/button-with-reflection/11.jpg">

Upvotes: 1

user38064
user38064

Reputation: 1

I think what you want to do is toggle between two declaration blocks. This can be easily done with the toggle method in the classList object. In order for this to be achieved, you must change the id selectors to class selectors.

document.querySelector('.list').classList.toggle('insert-class-name');

Upvotes: 0

Related Questions