Change Css with javascript when clicking

Asked

Viewed 922 times

4

I have a css circle and half of it is hidden. When you click on it, I want the hidden part to appear. When you click back, I want him to hide again. I made the following javascript code, the problem is: click, appear; click, hide; click again and nothing happens. I want you to keep showing up/hiding as many times as the user clicks.

$(".icone-btn").click(function() {
     $(".btn-contato").css("marginTop", "-170px");
        $(".icone-btn").click(function() {
        $(".btn-contato").css("marginTop", "-230px");
   });
});

2 answers

3


Create a class to manipulate this.

.margintop230 {
margin-top: -230px !important;
}

Leave already in the style of your circle the standard of -170px;

.btn-contato {
margin-top: -170px;
}

In javascript you will "toggle" the class . margintop230 every click:

$('.icone-btn').click(function(){
     $('.btn-contato').toggleClass('margintop230');
});

3

Every time you click, you’re creating a new Listener click that determines the margin as -230px. Solve with a single event handler. One of the ways is to toggle the margin values according to the current value:

$(".icone-btn").click(function() {
     var atual = .$(".btn-contato").css("marginTop");
     var nova = atual === "-170px" ? "-230px" : "-170px";
     $(".btn-contato").css("marginTop", nova);
});

Browser other questions tagged

You are not signed in. Login or sign up in order to post.