Connect an existing function to JQuery animation

There is a function in place that changes the background image of a vertical website when a navigation menu item is clicked.

<script type="text/javascript">
$(function() {
    $('a.panel-home').click(function(){
    $("#bgimg").attr('src',"<?php bloginfo('stylesheet_directory'); ?>/images/bg1.jpg");
    return false;
    });
});

I am trying to add an animation to this function so that the new background image fades in smoothly instead of changing abruptly. I want to achieve the effect using:

$("#bgimg").fadeIn(1500);

However, my JavaScript/jQuery skills are still developing and I'm not sure how to implement this properly.

Answer №1

Wrap your image within a div element and then add the effect to the div itself, as shown below:

HTML:

<div><img id="bgimg" src="...."></div>

JAVASCRIPT:

$(function() {
    $('a.panel-home').click(function(){
    $("#bgimg").parent().fadeOut(1000, function() {
        $("#bgimg").attr('src',"<?php bloginfo('stylesheet_directory'); ?>/images/bg1.jpg");
        $(this).fadeIn(1000); 
    });   
    return false;
    });
});

Answer №2

If you want to smoothly fade multiple images at the same time, you can achieve that with the code below:

/* This function is designed to be utilized on 'img' tags. It has been enhanced to accommodate more than one image for transitioning purposes. The first image should be in the options argument, while the subsequent images are provided in the more_images argument as a string array in the following format:
 * ["400|1000|apple.png","800|apple2.png", "apple3.png"]
 * Each element in the array consists of pipe-separated values representing delay, duration, and the image source.
 * With 3 elements present, they denote delay|duration|image
 * With 2 elements, they represent duration|image
 * And with only one element, it signifies the image itself. The default delay is zero and the default duration is 800 
 * 
 * If you intend to transition between just two images without additional animations, you can ignore the more_images argument.
 * External scripts can check if an animation is currently running by verifying the presence of the attribute data-anim in the parent div of the animated img element. This feature is valuable for external scripts to determine when transitions have concluded (e.g., within a setinterval call)*/
jQuery.fn.transictionto = function(options, more_images) {
      var settings = jQuery.extend({
   }, options || {});
   //wrap into div if no div is present.
   $(this).each(function() {
      if ($(this).parent('div').length == 0) {
         $(this).wrap('<div></div>')
      }
      //mark to check if animation is in being done
      $(this).parent().attr('data-anim','1');
      //now swap with background trick
      $(this)
      .parent()
         .css('background-image', 'url(' + settings.destinationImage + ')')
         .css('background-repeat', 'no-repeat')
      .end()
      .fadeOut(settings.duration, function() {
         this.src = settings.destinationImage;
         $(this).show();
         if (more_images != null && more_images.length) {
             var im = more_images.shift().split('|');//shift shrinks array
             var dly = im.length == 3 ? parseInt(im[0],10) : 0;
             var drt = im.length > 1 ? parseInt(im[im.length-2],10) : 800;
             $(this).delay(dly).transictionto({ destinationImage: im[im.length-1], duration: drt }, more_images);
         } else {
             $(this).parent().removeAttr('data-anim');
         }
      });
   });
}

$(function() {
    $('a.panel-home').click(function(){
        destImage = "<?php bloginfo('stylesheet_directory'); ?>/images/bg1.jpg";
        $("#bgimg").transictionto({ destinationImage: destImage, duration: 800 });
        return false;
    });
});

This time, ensure the transictionto() function is invoked on the img element.

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

Achieving consistent width for flex items in each row

Can I ensure that all flex items have the same width? Currently, my code looks like this: .video-container { background-color: blue; min-height: 90vh; display: flex; flex-wrap: wrap; } .video { flex: 1 0 25%; } <div class="video-contain ...

Creating multiple versions of a website based on the user's location can be achieved by implementing geotargeting techniques

It may be a bit challenging to convey this idea clearly. I am interested in creating distinct home pages based on the source from which visitors arrive. For instance, if they come from FaceBook, I envision a tailored home page for FaceBook users. If they ...

Looking to replicate a Modal that I designed, but unsure which elements need altering in order to achieve this. I am hoping to create three duplicates of the Modal

This modal is functioning perfectly, and now I want to replicate the same modal three times on a single page. I require three distinct buttons on the same page to trigger these separate modals. At this point, I am unsure which attributes need modification ...

Showing text in a textarea while maintaining formatting (such as using <br>)

Can someone help me with formatting a block of text like this: hello <br> how is your day <br> 123 To look like this: hello how is your day 123 I also need to display it in a textarea field. I attempted to do so using the following code: $ ...

Using Jquery to Submit a Form by Clicking a Button

Trying to implement a verification process on a Shopify e-commerce site where users have to confirm their country before proceeding to checkout. Initially used JavaScript's confirm(), but now experimenting with JQuery UI to incorporate HTML in the pop ...

Is there a way to successfully submit multiple locations, each separated by commas, through the multipart form?

Here is my HTML form: <form method="POST" enctype="multipart/form-data" v-on:submit.prevent="handelSubmit($event);"> <div class="clear"> <div class="col-md-3"></div> <div class="col-md-6"> <div class="form ...

Attempting to sort through an array by leveraging VueJS and displaying solely the outcomes

Within a JSON file, I have an array of cars containing information such as model, year, brand, image, and description. When the page is loaded, this array populates using a v-for directive. Now, I'm exploring ways to enable users to filter these cars ...

The CSS code seems to be ineffective when attempting to center elements with a specific width in react.js

Hey everyone, I'm currently working on developing a web application using react-bootstrap and I've encountered an issue with adjusting the width of my row and centering it. I have already created the necessary CSS and JS files, but I am unable to ...

Share on your Twitter feed

Currently seeking assistance in implementing a function on my website that allows users to post their individual posts to Twitter. For example: Message: "hello world" [twitter] By clicking on the twitter button, the message will be posted along with the p ...

Press the button to retrieve the div ID needed for a jQuery modal dialog box

I am currently utilizing a jQuery modal dialog box in the following manner: <div class="dialog-form" id="dialog-form1" title="Edit Invoice"> <form> .... inputs & selects </form> </div> <button class="dialog-but ...

The website runs quickly on my computer, but lags when deployed to the

With the development of my WordPress site that heavily utilizes custom Ajax for search result loading, I have encountered a discrepancy in performance between my local environment and VPS. On my HP laptop running WAMP, the site performs excellently with A ...

unrestricted motion through the utilization of css3 transitions and translations

When applying a new CSS translate, it's common practice to specify the exact number of pixels you want an element to move, such as 50px, 60px. This results in a relative movement from its current position. You can see an example of this here: http://j ...

Enhance your Angular material datepicker with additional content such as a close button

I'm currently working on customizing my Angular Material datepicker by adding a button. The goal is to have this button placed in the top right corner and enable it to close the datepicker when clicked. In addition, I also want to include extra conte ...

Understanding the percentages of CSS in relation to other elements

Can you define a CSS dimension in a percentage relative to an element other than its parent? Specifically, I want the border-radius of a div to be 10% of its width. However, using border-radius: 10% creates an elliptical border when the height and width ...

Select a date within the Bootstrap datetimepicker input

I implemented the datetimepicker widget from [insert link to the actual website here]. However, I encountered an issue as there was no clear guidance on how to use certain functions such as date, show, hide, etc. This made it challenging for me to set the ...

Tips for importing font files from the node_module directory (specifically otf files)

We cannot seem to retrieve the fonts file from the node module and are encountering this error message. Can't find 'assets/fonts/roman.woff2' in 'C:\Projects\GIT2\newbusinessapp\projects\newbusinessapp\src ...

concealing the date selection feature on the data picker

$('.year').datepicker({ changeMonth: true, changeYear: true, showButtonPanel: true, dateFormat: 'MM yy', onOpen: function(dateText, inst) { $("table.ui-datepicker-calendar").addClass('hide') }, onClos ...

Tips for finishing a row of images using CSS3

Here is the code snippet that I am currently working with: <div id="images" class="img"/> <img src="spiderman.png" alt=""/> <img src="superman.png" alt="" height="25%" width="25%"/> <img src="batman.png" alt="" /> </div> ...

"Although the ajax request was successful, the post data did not transfer to the other

i am working with a simple piece of code: var addUser = "simply"; $.ajax({ type: 'POST', url: 'userControl.php', data: {addUser: addUser}, success: function(response){ alert("success"); } }); on the page use ...

Removing page scrolling in Bootstrap 5: A step-by-step guide

I would like to ensure that only the card-body block is scrollable. Currently, the page does a bit of scrolling when the card-body block overflows (resulting in 2 scroll bars). The lorem text was added as an example of an overflow. The desired outcome is d ...