Change Background Image of DIV using jQuery

This tutorial explains how to change background image of a div at specific intervals using jQuery. Every element can have only one b...




This tutorial explains how to change background image of a div at specific intervals using jQuery. Every element can have only one background image at any point of time according to CSS and to make an element use multiple backgrounds, we have to cycle the images to change at regular intervals. This can be achieved by dynamically assigning background images using css() jquery method and adding a simple fadein/fadeout effect would make it look more neat.

This can be used for simple background image switches, for other image and content cycling that require heavy animations it is highly recommended to use one of the jQuery slider plugins or create one using jQuery UI effects.



1. Prepare background images and place it in a folder. Create a new html file in the same folder and copy paste the below code.


<html>
<head>
<script src="http://code.jquery.com/jquery-1.10.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
  $(window).load(function() {           
  var i =0; 
  var images = ['image2.png','image3.png','image1.png'];
  var image = $('#slideit');
                //Initial Background image setup
  image.css('background-image', 'url(image1.png)');
                //Change image at regular intervals
  setInterval(function(){   
   image.fadeOut(1000, function () {
   image.css('background-image', 'url(' + images [i++] +')');
   image.fadeIn(1000);
   });
   if(i == images.length)
    i = 0;
  }, 5000);            
 });
</script>
</head>
<body>
      <div id="slideit" style="width:700px;height:391px;">  
      </div>
</body>
</html>

Initially, when the page loads the first image is set as background image. After that for a period of every 5000 milliseconds the image is changed using setInterval function that executes periodically. To make the transition look more neat, I have added fadeIn/fadeout effects.




If you think this article and other information on this website is useful to you, please keep yourself subscribed via email or other social networking sites to be notified whenever more useful articles are posted here. Thanks for reading!



Subscribe to GET LATEST ARTICLES!


Related

Latest 1421167339148854348

Post a Comment

  1. A very nice tutorials! Thanks for the updates

    ReplyDelete
  2. Is this method reliable for browser compatibility?

    ReplyDelete
    Replies
    1. Hi Irene,

      We have used jQuery Fade in -out effects. As far as I know, it works well in all modern browsers and in IE from version 9 onwards. There are workarounds for making it work in IE8.

      Hope this helps!

      Thanks,
      Priya

      Delete
  3. Nice tutorial, is there anyway we can add pagination in the code?

    Thanks

    ReplyDelete
  4. how you can make a fade avoiding overlapping images to see for example the white background of the images?

    ReplyDelete
  5. Gracias por excelente material. Le quité el efecto de fadeIn-fadeOut y funciona de lo mejor.

    ReplyDelete
  6. You can use other functions other effect than the "#slideit"

    ReplyDelete
  7. Nice. But which function should I ad, so that the images are random? tx.

    ReplyDelete
  8. as you are using jquery already I would use .each to save two lines of code :)

    ReplyDelete
  9. This changing image process is difficult but not for experts because they can complete it in very short time. jQuery field has big scope and you can adjust in it easily. Dissertation writing service.

    ReplyDelete
  10. Thanks for the quality content that you have here. The National examination council has revealed that NECO Result Checker 2021 has been released. The result was released following the update of the NECO Scratch Card Price. Finally students are advised to get NECO Token for free here.

    ReplyDelete
  11. I have bookmarked your blog, the articles are better than other similar blogs.. thanks for a great blog!
    infected days

    ReplyDelete
  12. If you want to save a large amount of your money then click the link. So, visit here skillz discount code

    ReplyDelete
  13. If you want to save a large amount of your money then click the link and make a joyful future for you.
    Kyte Baby coupon

    ReplyDelete
  14. wordle website is an internet phrase recreation with a fun-filled puzzle theme for everybody. The participant's job is to guess and resolve the hidden phrases on the board. Gamers could have six makes an attempt to conjecture a five-letter phrase, with suggestions given for every guess within the type of coloured tiles indicating when the letters match or occupy the right place. The mechanics of this recreation are nearly just like the pen and paper Jotto recreation. Are you prepared to overcome the challenges? Be a part of Wordle at this time.

    ReplyDelete
  15. We offer a wide range of high-quality frames and sizes to suit any need and budget. portrait illustration

    ReplyDelete
  16. My friend from dissertation editing services told me that we have to cycle the images to change at regular intervals by dynamically assigning background images using css

    ReplyDelete
  17. This is a great tutorial for anyone wanting to learn how to change their background image using jQuery. The author provides clear and concise instructions, along with well-commented code snippets, making it easy to follow. I would definitely recommend their services to anyone in need of MBA assignment help in the New Zealand.

    ReplyDelete
  18. Amazing article! Thank you for sharing this article with us. This is very informative and useful. I glad to find out this article and now I’m going to bookmark this one best plastic surgeon in UAE.

    ReplyDelete
  19. kfc coupons 2023 is one of the most popular restaurants all over the world when it comes to delicious comfort food. KFC, which stands for "Kentucky Fried Chicken" is a chain of fast-food restaurants in the United States that specializes in fried chicken and has its headquarters in Louisville, Kentucky. During the Great Depression, businessman Colonel Harland Sanders (1890-1980) started selling fried chicken from a roadside eatery in Corbin, Kentucky.

    ReplyDelete
    Replies
    1. Our team spends countless hours searching for and organizing deals and discount codes for knowfashionstyle coupons We publish thousands of new codes every day, constantly scouring multiple sources for the most recent Knowfashionstyle coupon codes, as well as seeking out the best coupons, non-coupon deals, and ways to save money at Knowfashionstyle,

      Delete
  20. I just finished reading your article on changing background images with jQuery, and it's exactly what I needed! Your step-by-step guide was easy to follow, even for someone like me who's still getting the hang of jQuery. https://frono.uk/comfort-series-hot-tub/

    Your explanation of each line of code and how it contributes to the overall functionality was spot-on. I've been struggling with implementing dynamic background changes on my website, but your article made it seem like a breeze. Thanks to you, I now have a much clearer understanding of how to use jQuery to manipulate background images effectively.

    Keep up the awesome work, and please keep sharing your knowledge—I'll revisit your blog for more helpful tips and tricks!

    ReplyDelete
  21. I have to admit, I was a bit apprehensive about tackling this topic, but this article made all the difference! The writer’s clear and concise explanations transformed my understanding entirely. It’s such a relief to see something so complex presented in such a user-friendly manner. Kudos for a job well done! Visit our link for ISO Certification in Saudi Arabia

    ReplyDelete
  22. This tutorial makes changing background images with jQuery super easy! A great resource for web developers looking to enhance their sites. Visit our link for ISO Certification In Philippines

    ReplyDelete
  23. Thanks for sharing informative blog.You should also write some health and lifestyle blogs
    .

    ReplyDelete
  24. Tyres Enville
    Enville is a hamlet on the A458 motorway and is located very close to the market town of Stourbridge. If you often drive past the Enville Golf Course, then you may keep the contact details of Kingswinford Tyres handy. We are often called by the local motorists for onsite repairs and mobile tyre fitting Enville.

    Our garage is located roughly 5 miles away from Enville. Therefore, when you call us for an emergency tyre replacement service, we can reach out to you within 12 minutes.

    So, be sure to give us a call on 01384 401656 the next time you get stuck due to any emergency.

    Benefits Of Our Mobile Tyre Fitting Service
    We advise our clients to book a mobile tyre fitting solution to enjoy the following advantages:

    24/7 tyre replacement service at your preferred location
    Hassle-free online booking option
    Highly competitive pricing
    Professional service in the minimum turnaround time
    Moreover, we deliver the tyres you select online and take your vehicle’s old tyres back to the garage for proper, eco-friendly disposal.

    So, you can finally stop looking for ‘mobile tyre fitting near me’ and rely on our experts instead.

    Buy Tyres Enville From Us
    Now, you can avoid the hassle of long queues for tyre bookings. Consider using the tyre finder tool on our homepage. Using it, you can discover various premium, mid-range and cheap tyres Enville for your vehicle.

    Throughout the year we sell the following the tyre variants:

    Summer Tyres
    All-season Tyres
    4x4 Tyres
    Performance Tyres
    Run-flat Tyres
    Winter Tyres
    You can send us a message for personalised tyre recommendations at sales@kingswinfordtyres.co.uk. We will send a detailed response addressing your query.

    Opt For Car Servicing
    We recommend car servicing at regular intervals to avoid issues like poor fuel economy, MOT test failures, sudden drop in performance, and a lot more. At our garage, you may avail either interim or full servicing based on the last servicing date of your car.

    Moreover, you can avail the following services from time to time:

    Wheel Alignment
    Puncture Repair
    Air Condition Re-gas
    Brakes Replacement
    Exhaust Service
    Wheel Balancing
    Car Battery Service
    24/7 Emergency Callout, etc.
    To get these services, kindly book a session and visit our facility at Unit 2, Dawley Brook Road Kingswinford West Midlands DY6 7BD. We will be offering you the best solutions on budget.

    ReplyDelete

emo-but-icon
:noprob:
:smile:
:shy:
:trope:
:sneered:
:happy:
:escort:
:rapt:
:love:
:heart:
:angry:
:hate:
:sad:
:sigh:
:disappointed:
:cry:
:fear:
:surprise:
:unbelieve:
:shit:
:like:
:dislike:
:clap:
:cuff:
:fist:
:ok:
:file:
:link:
:place:
:contact:

SUBSCRIBE


Hot in weekRecentComments

Recent

Spring Security 4 for Spring MVC using Spring Data JPA and Spring Boot

I have been writing a series of tutorials on using Spring Security 4 in Spring MVC application starting from the basic in-memory authentication. In this post, I am writing a step by ste...

Spring Security JDBC Authentication with Password Encryption

I published a basic level tutorial on how to implement JDBC Authentication and Authorization using Spring Security last week. There are few best practices to be followed while implementing secur...

Spring Security 4 - Simple JDBC Authentication and Authorization

In one of my articles, I explained with a simple example on how to secure a Spring MVC application using Spring Security and with Spring Boot for setup. I am going to extend the same example to ...

Java String Split with Pipe Character Not Working - Solution

If you are working on Java, you might have run into this issue when you try to split a string based on a pipe character ("|"). It simply won't work. Split method in Java takes regex as an argumen...

Comments

waqas blog:


business help sport business grow for need help thanks for sharing post
ECM online shop
ECMonlineshop

We Care India:

You're really doing your best work here, keep it Keyword!

Ninja:

A very well-written and thought-provoking post. It offers practical tips and a fresh perspective on the topic5-16-2025

Jack Harrison:

Great insights on 2015 web design trends! It's amazing to see how responsive layouts and flat design started shaping modern user experiences. Looking forward to how these foundations continue evol...

item