The animation is failing to display in the Jquery function

I've successfully created two versatile functions that can be used with various CSS classes.

    var CSSElement;
$(document).ready(function(){  


  expandBox (".orange");
  minimizeBox(".orange");

});

function expandBox ($CSSElement){
     //When the mouse hovers over  
    $($CSSElement).mouseover(function(){  
        $(this).stop().animate({height:'485px'},{queue:false, duration:600, easing: 'easeOutBounce'})  
    });     
}

function minimizeBox ($CSSElement){
     //When the mouse is moved away
    $(CSSElement).mouseout(function(){  
        $(this).stop().animate({height:'50px'},{queue:false, duration:600, easing: 'easeOutBounce'})  
    }); 
}

Despite my efforts, only the expandBox function appears to work properly. Unfortunately, when I move my cursor away from the .orange element, the box fails to contract as intended.

I intend for these animations to be reused multiple times throughout my website, hence why I want them to be encapsulated within functions. Interestingly, when I structure my code like this:

$(document).ready(function(){  

   //When the mouse hovers over  
    $($CSSElement).mouseover(function(){  
        $(this).stop().animate({height:'485px'},{queue:false, duration:600, easing: 'easeOutBounce'})  
    });  

  //When the mouse is moved away
    $(CSSElement).mouseout(function(){  
        $(this).stop().animate({height:'50px'},{queue:false, duration:600, easing: 'easeOutBounce'})  
    }); 

});

Surprisingly, everything works fine in this setup. Can anyone explain why the first code doesn't work but the second one does?

Thank you,

vnayak

Answer №1

It seems like there was a mistake in your coding:

$($CSSElement)

$(CSSElement)

This could be why the functionality isn't working.

Answer №2

Within JavaScript, the use of $ as a character in identifiers is perfectly acceptable (unlike C where it's completely forbidden or PHP and Perl where it serves as a special sigil). This means that $CSSElement and CSSElement are considered distinct identifiers - if one is defined, the other will not function. The expressions $($CSSElement) and $(CSSElement) are separate entities.

(The practice of prefixing variable names with $ can be potentially confusing; in JavaScript, they work fine without this convention.)

The scenario at hand unfolds as follows:

  1. Both functions employ a parameter named using $.
  2. expandBox utilizes this parameter with the $ symbol.
  3. minimizeBox, on the other hand, uses it without the $ sign (resulting in the utilization of an unrelated variable).

My recommendation: Refrain from utilizing prefixed $ in your code; adapt your approach as shown below:

function expandBox (CSSElement){
     //When mouse rolls over  
    $(CSSElement).mouseover(function(){  
        $(this).stop().animate({height:'485px'},{queue:false, duration:600, easing: 'easeOutBounce'})  
    });     
}

function minimizeBox (CSSElement){
     //When mouse is removed  
    $(CSSElement).mouseout(function(){  
        $(this).stop().animate({height:'50px'},{queue:false, duration:600, easing: 'easeOutBounce'})  
    }); 
}

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

Navigating cross-domain errors and managing Windows Communication Foundation (WCF)

I encountered an issue while attempting to make a cross-domain jQuery AJAX call to my WCF webservice. Initially, I used the CORS approach but found that the error block was not triggering as expected. However, when I switched to the jsonp approach, it work ...

Error encountered while making a REST API call in Ajax: Unforeseen SyntaxError: Colon unexpected

I am currently troubleshooting my code to interact with a REST API. My platform of choice is "EspoCRM" and I aim to utilize its API functionalities. The official documentation recommends using Basic Authentication in this format: "Authorization: Basic " ...

The issue I am facing is that the "return false" statement does not seem to be effective in my jQuery AJAX

Apologies to everyone.. :( it seems I missed including the jquery library... My bad! :3 Feeling quite exhausted at the moment. Could someone please point out what's wrong with my code? The 'returning false' isn't functioning as expecte ...

Adjust the font size of the Facebook Comments Plugin

Does anyone know how to adjust the font size within a Facebook Comment iframe? I attempted to utilize a jquery script with the append method in hopes of injecting my CSS file into the iframe, but unfortunately it did not yield any result. Is modifying the ...

How come this state remains bound to this function even after it has been updated? - Using NextJS version 13.3.0 with React

A unique scenario arises where a button triggers the display of a modal created using a dialog HTML element. This button is stored in a state (thingsToRender) based on a condition, which is simulated within a useEffect hook. The issue lies in the fact that ...

The minDate function is malfunctioning when used in conjunction with a date picker that includes a time

I am struggling with the date & time picker not working correctly in the following function. I suspect there is a conflict between the minDate function of the jQuery UI time picker. I have tried changing the script location and removing the minDate funct ...

The issue of linking .then() functions

I've been struggling to grasp the concept of Promises/then-ables for a while now. Currently, I am working with NextJS. My goal is to chain together the following steps: Retrieve data from an API Save the data Modify the data to create a component (w ...

AngularJS: A Step-By-Step Guide to Adding Two Values

Currently, I am utilizing the MEAN stack for my application with AngularJS as the front-end. I have two tables in which I obtained total sum values like 124.10 in the "conversion rate" column. Now, I am looking to calculate the total sum of the "conversion ...

Is it possible to utilize ag-grid's API to filter multiple checkbox values simultaneously?

I am currently utilizing angularjs and have implemented a series of checkboxes to filter my ag-grid. So far, I have successfully utilized radio buttons and the api.setQuickFilter method for filtering based on individual values. However, I am facing an iss ...

Is there a way to convert a PDF file to a Javascript array using a

Is there a way to extract only words from a PDF document using JavaScript? I am not interested in images, digits, or tables - just the words so that I can manipulate them as JavaScript objects. ...

A function in Angular 2 that subscribes to an Http Observable callback

I am facing an issue with the .subscribe function in my code. Firstly, I have a function that sends a request to the server. protected sendRequest(data:string,url:string):Observable<any>{ let headers = new Headers({ 'Content-Type': &a ...

Locate the iframe that invoked a function within its parent element

There are multiple iframes on a page that showcase ads unicorns and bacon to users. Due to the impossibility of detecting an iframe's domready event from the parent (please correct me if I'm wrong), each iframe contains initialization code like t ...

Error message: A boolean type cannot be used as a function in the fullcalendar ajax call

I have successfully implemented a fullcalendar into my app and have added a method to filter results by user: function filterEventsByProvider(selected_provider) { $('#calendar').fullCalendar('removeEvents'); $('#calendar&a ...

Animating the background color of a div vertically from the center using CSS3 or jQuery

I am attempting to achieve a similar effect to the right navigation on the following website: Using jQuery to create the effect where the color expands from the center is what I am aiming for. However, since that particular site was built using Flash, I a ...

I am looking to implement a function in JavaScript that will prevent the next button from being enabled until all options

I have a total of 6 dropdown menus along with a next button and previous button. I want the next button to be disabled until all 6 dropdown menus are filled out. Once all 6 dropdown menus are filled, the "next" button should become enabled. Below is the c ...

Is there a way to expand this embedded video so that it spans the entire width of the screen

I have a code snippet with one row and two columns. I would like to embed a video from Vimeo in the first column so that it fills the entire column without any padding. Additionally, I want the two columns to be right next to each other with no space betwe ...

When utilizing the data-target attribute, the Bootstrap dropdown becomes toggled

My Bootstrap dropdown is giving me trouble when I use it with data target. Removing data-target from the button makes it work, but then my website's dropdown only opens on the second click. So I tried using data-target to fix it, but now it won' ...

Understanding how to properly handle the data sent by an ajax request in a NodeJS server

I currently have an array called passedWord = ['a', 'bbb']. I am then making an AJAX request to send this array to a Node.js server. Upon receiving the array on the server, Body Parser returns the following object: { name: 'abc&ap ...

Meteor: Locate the closest transportation option between two locations

I'm currently in the process of developing a carsharing app, and when it comes to setting up rides, I have this kind of data structure stored in my database: { "_id": "YyPpkCDhTKStGw6CL", "authorId": "W6zvbcqit4Mw6a2iK", " ...

The Date picker is unresponsive to clicks when inner html is being used

When I tried to use the code below, I found that I am unable to select the data picker while using the inner HTML. Can anyone help me figure out what I am doing wrong? Thanks in advance. Below is my code snippet: $(document).ready(function(){ /*Date Pic ...