Home  >  Article  >  Web Front-end  >  How to change the width of a div using jQuery

How to change the width of a div using jQuery

PHPz
PHPzOriginal
2023-04-10 09:47:41913browse

jQuery is a JavaScript library that helps developers write cleaner, faster code. In the development of web applications, jQuery is an indispensable tool. This article will introduce how to use jQuery to change the width of a div.

First, we need to introduce the jQuery library into the HTML page. It can be introduced in the following way:

<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>

This will give our page the ability to use the jQuery library.

Next, we need to add styles in CSS to set the initial width of the div that needs to change the width. For example:

div {
    width: 100px;
}

Now, we can use jQuery to change the width of the div. You can use the following code:

$(document).ready(function(){
  $("button").click(function(){
    $("div").animate({width: "400px"}, 1000);
  });
});

Explain the above code:

  • When the page has been loaded, use the $(document).ready() function .
  • When the button is clicked, execute a function.
  • In the function, use the animate() function to change the width of the div.
  • The first parameter is an object containing the CSS property to be changed and its target value.
  • The second parameter is the duration of the animation, in milliseconds.

The above code will increase the width of the div from 100px to 400px and animate it in 1 second.

If you want to increase or decrease a certain number of pixels based on the current width, you can use the following code:

$("div").width(function(index, width){
  return width + 50;
});

This will increase the width of the div by 50 pixels.

Summary

In this article, we introduced how to change the width of a div using jQuery. This can be achieved by using jQuery's animate() function and width() function. Using the jQuery library, we can easily write interface animations to make the page experience smoother and more beautiful.

The above is the detailed content of How to change the width of a div using jQuery. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn