skip to Main Content

I am trying to make a button that, when I click the button, set position to left=0px; of a element and when further clicked set position to right=0px; and continue toggling when clicking.

But it failed because it write ass inline CSS. without toggleClaas and adding CSS property How can I do this with JQuery?

My Code:

$(".something").click(function(){    
  $(".name").animate({left: "0px"},1000);

  //when again clicked do this event
  //$(".name").animate({right: "0px"},1000);
});

Instead of

$(".something").click(function(){    
  $(".name").toggleClass("active");
});

CSS:
.name{left: 0px;}
.active{right: 0px;}

2

Answers


  1. Try this

    let isLeft = true;
    $(".something").click(function(){    
        const move = isLeft ? { left: '0px' } : { right: '0px' };
        $(".name").css('left','unset').css('right', 'unset');
        $(".name").animate(move,1000);
        isLeft = !isLeft;
    });
    
    Login or Signup to reply.
  2. You can do it by initializing the button by right:0px then whenever you click the position will change as follows :

    $("#something").click(function(){    
      $(this).toggleClass("right");
      $(this).toggleClass("left");
    });
    div.a {
      position: relative;
      width: 400px;
      height: 200px;
      border: 3px solid red;
    }
    
    div.a button {
      position: absolute;
    }
    
    .left{left: 0px;}
    .right{right: 0px;}
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div class="a">
    <button type="button" id='something' class='right' onclick="console.log('Hello world!')">Click Me!</button>
    </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search