How to create jQuery slide left and right toggle effect

  151 views   2 months ago jQuery

Use the jQuery animate() method

There are no such method in jQuery like slideLeft() and slideRight() similar to slideUp() and slideDown(), but you can simulate these effects using the jQuery animate() method.

Let's take a look at the following example to understand how it basically works:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery slideLeft and slideRight Effect</title>
<style>
    .box{
        float:left;
        overflow: hidden;
        background: #f0e68c;
    }
    /* Add padding and border to inner content
    for better animation effect */
    .box-inner{
        width: 400px;
        padding: 10px;
        border: 1px solid #a29415;
    }
</style>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script>
    $(document).ready(function(){
        var boxWidth = $(".box").width();
        $(".slide-left").click(function(){
            $(".box").animate({
                width: 0
            });
        });
        $(".slide-right").click(function(){
            $(".box").animate({
                width: boxWidth
            });
        });
    });
</script>
</head>
<body>
    <button type="button" class="slide-left">Slide Left</button>
    <button type="button" class="slide-right">Slide Right</button>
    <hr>
    <div class="box">
        <div class="box-inner">Lorem ipsum dolor sit amet...</div>
    </div>
</body>
</html>

There is an even better way to create this effect. The following example will slide toggle the box from right-to-left and left-to-right something like slideToggle() effect.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery Slide Left and Right Toggle Effect</title>
<style>
    .box{
        float:left;
        overflow: hidden;
        background: #f0e68c;
    }
    /* Add padding and border to inner content
    for better animation effect */
    .box-inner{
        width: 400px;
        padding: 10px;
        border: 1px solid #a29415;
    }
</style>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script>
    $(document).ready(function(){
        $(".slide-toggle").click(function(){
            $(".box").animate({
                width: "toggle"
            });
        });
    });
</script>
</head>
<body>
    <button type="button" class="slide-toggle">Slide Toggle</button>
    <hr>
    <div class="box">
        <div class="box-inner">Lorem ipsum dolor sit amet...</div>
    </div>
</body>
</html>

 

Author : Harsukh Makwana
Harsukh Makwana

Hi, My name is Harsukh Makwana. i have been work with many programming language like php, python, javascript, node, react, anguler, etc.. since last 5 year. if you have any issue or want me hire then contact me on harsukh21@gmail.com

Related Articles