Your code is fine ... or almost. It is simpler than some of the proposed solutions and all you have to do is correct a very simple error. If you notice, in the comparison to determine in which position is the element #work2
instead of checking the position of #work2
, you check the position of #flecha_work
! :
// aquí deberías estar comprobando work2
if(flechaWork.style.left=="50%"){
work.style.left="-60%";
work.style.transition = "all 1.3s";
}
else{
work.style.left="50%";
work.style.transition = "all 1.3s";
}
Since then in the code what you change is the #work2
style, the condition will always go by the else
and that's why you do not see the actions alternate .
The solution: change the condition so that the position of #work2
is checked:
if(work2.style.left=="50%"){
And then the actions already alternate without problems:
window.addEventListener("load",function(){
var flechaWork=document.getElementById('flecha_work');
var work=document.getElementById("work2");
flechaWork.addEventListener("click",function(){
if(work.style.left=="50%"){
work.style.left="-60%";
work.style.transition = "all 1.3s";
}
else{
work.style.left="50%";
work.style.transition = "all 1.3s";
}
})
})
#work2 {
position:absolute;
top:100px;
left:-60%;
width:100px;
height:200px;
color:white;
background:black;
}
<button id="flecha_work">Pulsame, soy flecha_work</button>
<div id="work2">
Soy Work2
</div>