Javascript/jQuery for enlarging and shrinking a div

Struggling with a function I'm implementing for a website. My goal is to move and expand a div upon button click, with the text on the button changing to "close". When the close button is clicked, the div should return to its original position.

I've been trying everything but just can't seem to get it right.

Here's where I'm at so far:

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script> 

var text = 1;

$('button').click(function(){
    if(text == 1){
        $("div.div1").toggleClass("animateSlide");
        $('button').html('Go Back');
        text = 0;
    } else{
        $("div.div1").toggleClass("animateSlide");
        $('button').html('Start Animation');
        text = 1;
    }
});
</script> 
</head>
<body>

   <div class="container-fluid">
      <div class="row-fluid">

         <div class="col-xs-12 v-center">
            <div class="content text-center">

               <div class="col-xs-4 animated slideInRight  ">
                 <div class="div1"><button>Start Animation</button></div>
               </div>

               <div class="col-xs-2 animated slideInRight"> <a href="#">hello</a>
               </div>

               <div class="col-xs-2 animated slideInRight"><p>hello</p>
               </div>

            </div>
         </div>


         <style>
           .div1{
              transition: all .5s;
              background:#98bf21;
              height:100px;
              width:100px;
              position:absolute;
           }

           .animateSlide{
              width: 150px;
              height: 150px;
              opacity: .5;
              margin-left:100px;
           }
         </style>
     </body>
   </html>

Answer №1

To implement a separate class for toggling animations, follow these steps:

var isAnimated = false;

$('button').click(function(){
    if(isAnimated){
        $('div').toggleClass('animated');
        $('button').html('Start Animation');
        isAnimated = false;
    } else{
        $('div').toggleClass('animated');
        $('button').html('Stop Animation');
        isAnimated = true;
    }
});
div{
    transition: all .5s;
    background:#98bf21;
    height:100px;
    width:100px;
    position:absolute;
}

.animated{
    width: 150px;
    height: 150px;
    opacity: .5;
    margin-left:100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div><button>Start Animation</button></div>

Answer №2

Transfer the second animation function as a callback to the initial function.

(See Demo)

$(document).ready(function(){
    var counter = 0;
    $("button").click(function(){
        $("div").animate({
            left: ++counter % 2 * 100,
            opacity: '0.5',
            height: '150px',
            width: '150px'
        }, 'fast', function() {
            $(this).animate({
                width: "100px",
                height: "100px"
            }, 500);
        });
    });
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The jQuery included does not function properly in production mode and results in an error stating that it is not a function

After placing the jquery.placeholder.js file in the assets/javascripts folder, I successfully applied the function in my coffeescript file and it worked perfectly. $(document).ready -> $('input, textarea').placeholder(); However, when swit ...

Creating a triangle number pattern in JavaScript with a loop

Hi there, I'm currently facing an issue. I am trying to generate a triangular number pattern like the one shown below: Output: 1223334444333221 =22333444433322= ===3334444333=== ======4444====== I attempted to write a program for this, however, ...

Retrieving the previous value using JQuery's onChange event

Is there a way to retrieve the initial quantity value before it is changed with the onChange function in this code snippet? I'm encountering issues with the CSS while using this setup for an input box. You can view the problematic CSS here. Updating ...

How can I use a JavaScript or jQuery function to choose a specific audio track that is currently playing locally?

Currently, I have developed a music app that features local mp3 files triggered by clicking on divs which are linked to the audio using an onClick function with the play() method. Additionally, there is a scrolling screen that displays the song's arti ...

Group in group, glitch in outdated browser

Facing an issue with IE6 while writing HTML/CSS code. I am looking to create dynamic divs using classes: Here is a simple example (not real-project code): .top {width: 50px;} .top.selected {background: #f00;} .mid {width: 114px;} .mid.selected {backgrou ...

Ways to ensure that the form data stays consistent and visible to the user continuously

Is there a way to ensure that the user submits the form, stores it in a MYSQL database, and then displays the same submitted data in the form field? <div class="form-group"> <label class="control-label col-sm-2" for="lname">Last Name*</l ...

What steps should I take to successfully integrate my Dojo DataGrid into a Dojo ContentPane that is nested within a Dojo TabContainer?

It seems that the issue arises from having different settings for parseOnLoad in the separate widgets. I have experimented with both true and false values but without success. To troubleshoot, I created three web pages - two containing TabContainer and Dat ...

Looking to create a dynamic Angular reactive form using API response data? Seeking guidance on how to achieve this? Let's

[ { "name": "jkjk", "firstName": "hgh", "lastName": "ehtrh", "replytype": "svdv", "prodCode": "svv", "execu ...

Is there an equivalent of HtmlSpecialChars in JavaScript?

It seems that finding this is proving more difficult than anticipated, even though it's such a simple concept... Is there an equivalent function in JavaScript to PHP's htmlspecialchars? While it's possible to create your own implementation, ...

My script works perfectly during $(document).ready(function() execution on a local server, but encounters issues when run

I am facing an issue with my $(document).ready(function() code that only seems to work locally. I'm not sure what the problem is, but here is an example of the code. Thank you for any assistance. <a href="#"><img src=images/folder_icon.png i ...

What is the best way to align all of my content to the center in HTML?

In my web design class, I encountered an issue while creating a page. Currently, my page consists of a navigation bar and an image. I wanted to center both elements using CSS. display: block; margin-left: auto; margin-right: auto I applied this CSS to th ...

Ensure that the image within the child div occupies the entire height of the parent div

I'm having a bit of trouble figuring this out and could use some input: There's a parent div with an unspecified height, determined by its content. Inside this parent div are two 'child' elements; however, I want only one to dictate t ...

What is the best way to manage HTML code that is delivered through JSON data?

I am dealing with data from a JSON that is in HTML code format. I need to print it as HTML, but currently it is only printing as a string: "content": "More tests\u003cbr /\u003e\n\u003cbr /\u003e\n\u003cdiv class=&bso ...

What is the most effective way to display a star rating determined by the average score?

Currently, I am working on a project using Django and Jquery. The task at hand is to display hotel ratings with stars colored in orange based on an average score obtained from user votes. Let me provide you with an example: score = 8 vote= 2 average = 4 T ...

The function is failing to trigger when clicked within an Angular 5 app

Hey everyone, I'm facing a minor issue with my Angular 5 project. I am trying to use a common session check method from a shared TypeScript file. This method is used both when the page loads and when the logout button is clicked to redirect the user t ...

Having trouble with JSON parsing in Promise execution

I am in the process of developing a Promise with the objective of adding up any numbers discovered within an array or JSON object. The add() function is designed to receive a series of URLs as a string input and calculate the total sum of those URLs. Her ...

Determining the most appropriate time to utilize the 'async' built-in function in ES2017 versus implementing 'npm i async' can depend on a variety of factors such

I recently discovered that async/await is a feature of ES2017, however, in some of my previous projects I had to use the package async to implement async/await functionality. Is there a simple way to determine when async can be used without importing it? ...

Can an infowindow be automatically closed based on specific criteria?

Show the infowindow only when hovering over the marker. It should disappear when moving the mouse away from the marker. The infowindow should stay open only if you click on the marker, and can be closed by clicking the close button on the infowindow. ...

Disregard the stylesheet that has been provided

I'm currently working on a website using a template that includes a stylesheet. Unfortunately, the stylesheet is causing issues with elements I add such as Google Maps or other custom features on my site. Is there a way to prevent the following tag fr ...

Having trouble getting dynamic values to render properly in Ionic select? Find a solution in Ionic 4

Encountering an issue with Ionic 4 and ion-select. The problem arises when attempting to bind data, specifically when preselecting data. In this scenario, the ion-select element fails to render properly. <ion-item class="transparent"> ...