Is it possible to toggle between hide and show functions using Jquery?

I have a question about two jquery functions that I've been struggling with.

$(document).ready(init); 
  function init() { 
  $(".alphaleft").hover(function (g) { 
  $(".boxy,.yee").show(); 
  }, 
  function (g) { 
  $(".boxy,.yee").hide(); 
  }); 
}

$(document).ready(init); 
  function init() { 
  $(".alpharight").hover(function (h) { 
  $(".tea,.coffee").show(); 
  }, 
  function (h) { 
  $(".tea,.coffee").hide(); 
  }); 
} 

The issue is that only one function shows up at a time. If I comment out one, then the other works fine and vice versa. I can't figure out what's causing this inconsistency. Any suggestions or advice would be greatly appreciated, as I've been trying to solve this for an hour now and it's driving me crazy!

edit: http://jsfiddle.net/W3TTh here is my jsFiddle link for reference!

Answer №1

Utilize anonymous functions when passing them to the ready function.

$(document).ready(function(){ 
   $(".alphaleft").hover(function (g) { 
    $(".boxy,.yee").show(); 
   }, 
   function (g) { 
    $(".boxy,.yee").hide(); 
   }); 
});

$(document).ready(function () { 
  $(".alpharight").hover(function (h) { 
    $(".tea,.coffee").show(); 
  }, 
  function (h) { 
    $(".tea,.coffee").hide(); 
  }); 
});

To avoid conflicts caused by naming functions the same, it is important to use unique names for each function declaration. By using anonymous functions within a closure, you can prevent one function from overriding another function with the same name at the global scope.

You can see this issue in action on this example fiddle. Rearranging your code also highlights the problem:

//Init function created  
function init() { 
  $(".alphaleft").hover(function (g) { 
  $(".boxy,.yee").show(); 
  }, 
  function (g) { 
  $(".boxy,.yee").hide(); 
  }); 
}

//Init function overridden
function init() { 
  $(".alpharight").hover(function (h) { 
  $(".tea,.coffee").show(); 
  }, 
  function (h) { 
  $(".tea,.coffee").hide(); 
  }); 
}

//Init function called 2x after being overridden
$(document).ready(init);
$(document).ready(init);

Answer №2

Avoid having duplicate ready functions and unnecessary calls to a separate init function:

$(document).ready(function() { 
  $(".alphaleft").hover(function () { 
      $(".boxy,.yee").show(); 
  }, function () { 
      $(".boxy,.yee").hide(); 
  }); 

  $(".alpharight").hover(function () { 
      $(".tea,.coffee").show(); 
  }, function () { 
      $(".tea,.coffee").hide(); 
  }); 
});

Answer №3

The reason for the issue is that you're redeclaring the init function. To resolve this, consolidate it into a single function as shown below:

$(document).ready(init); 
function init() { 
    $(".alphaleft").hover(function (g) { 
        $(".boxy,.yee").show(); 
    }, 
    function (g) { 
        $(".boxy,.yee").hide(); 
    }); 
    $(".alpharight").hover(function (h) { 
        $(".tea,.coffee").show(); 
    }, 
    function (h) { 
        $(".tea,.coffee").hide(); 
    });    
}

For a demonstration, check out this functioning example: http://jsfiddle.net/Abc123/

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

Unusual glitch with paint/rendering in Safari while navigating through a lengthy list of content

Encountering a peculiar problem where a page displaying a grid of boxes is experiencing issues in Safari, Chrome on iPhone 11 Pro, iPhone 13 Pro, and Chrome on Pixel 4a. Other devices are not affected. Symptoms include unresponsiveness and blank sections a ...

Generating elevation graph from a kml file with the combination of php and javascript

Currently, I am exploring the Google Elevation Service with the goal of creating an elevation profile similar to the one showcased in this example: Below is the JavaScript code snippet used: var elevator; var map; var chart; var infowindow = new google.m ...

Is it possible to establish a standard view for the date/time input field, disregarding the user's

When working with a Django Form, I am incorporating a datepicker. While the solution may involve JS and HTML, my query remains specific. date_field= forms.DateField( input_formats=['%Y-%m-%d'], widget=forms.DateInput( format=& ...

Attempting to retrieve data from cloud Firestore utilizing keyvalue in Angular

My database stores user information under the 'users' collection. I can access this data using the following code: In my service: users$ = this.afs.collection<Users[]>('users').valueChanges(); In my component: public users = t ...

choose to display on mobile devices as a dropdown menu rather than a modal window

On mobile devices, my select elements are currently displayed as modals with options. However, I need to change this appearance to resemble the dropdown list view observed on desktop devices. Your assistance is greatly appreciated. ...

Creating a tool to display mouse coordinates as a pointer on an HTML5 canvas

I'm struggling with mouse coordinates while working on canvas in HTML5. My approach involves using JavaScript for drawing on the canvas. Below is my current code to track the mouse pointer within the canvas: $('#canvasID').mousedown(functi ...

Fantastic code snippet for fixing rendering issues with jQuery AJAX

Can someone help me troubleshoot this issue with a Sublime Text snippet not rendering from the keyboard shortcut? <snippet> <content><![CDATA[ var url = ''; var jqxhr = $.ajax(url) .done(function() { console.log(& ...

Reacting to a situation where the tailwind grid has an issue: the responsive column span is visible in the HTML, but

I'm having an issue with a grid that is not behaving as expected. I have set up a jsfiddle to show the behavior I am looking for, which relies on the responsive code: col-span-3 md:col-span-2 for one of the items. The problem arises when I inspect th ...

Incorporating external function from script into Vue component

Currently, I am attempting to retrieve an external JavaScript file that contains a useful helper function which I want to implement in my Vue component. My goal is to make use of resources like and https://www.npmjs.com/package/vue-plugin-load-script. Thi ...

What are the recommended methods for updating data using mongoose?

There are two methods for updating data with mongoose. Using model methods, such as User.updateOne({username}, {$set: {age}}) Finding the document, making changes to its properties, and saving it. Like this: const user = await User.findById(userId) user. ...

The function Yii2 isAjax returns a boolean value of false

Encountered an issue while attempting to run some code, even though it worked previously. Using AJAX to execute the code, but it resulted in a 500 error. Came across several posts with similar issues and their solutions, but none of them resolved the iss ...

Unable to retrieve JSON data from converting TXT using JavaScript, resulting in undefined output

After converting txt to JSON, I encountered an issue. const txt = JSON.stringify(`{ ErrorList: [{ 80: 'Prepared' }], Reference: [ { 'Rule Name': 'Missing 3', 'Rule ID': 1, 'Rule Des& ...

Unable to clear cache in Next.js using RTK query

Currently, I am utilizing Next.js along with next-redux-wrapper and RTK Query. My application is performing external API requests on the server side. The implementation of the request looks like this: CompaniesPage.getInitialProps = initialPagePropsWithCom ...

Upon installing a global npm package, the system encountered an error stating: 'File or directory not found: ENOENT'

After successfully publishing my first Node.js CLI tool package on npm, I encountered an issue when trying to test it by installing it locally. The warning message "Error: ENOENT: no such file or directory" kept showing up. Steps for Reproduction To start ...

Troubleshooting issue: Angular not resolving controller dependency in nested route when used with requirejs

When the routes are multiple levels, such as http://www.example.com/profile/view, the RequireJS is failing to resolve dependencies properly. However, if the route is just http://www.example.com/view, the controller dependency is resolved correctly. Below ...

Node.js Binary Search Tree - Error: Identifier Not Found

A program run through node.js has been developed to create a binary search tree with various methods like insert, remove, and print. The program is divided into two separate files: Tree.js, which exports the functions Tree() along with its methods and test ...

Using Django and jQuery to retrieve a file and display a prompt for downloading the file in the browser

Previously, I had a question about passing files to the browser for download, which was easily achieved by passing strings created at the end of a function to an iframe's src attribute. Now, I have a more complex task at hand – I need to pass pre-e ...

Find out if OpenAI's chat completion feature will trigger a function call or generate a message

In my NestJS application, I have integrated a chat feature that utilizes the openai createChatCompletion API to produce responses based on user input and send them back to the client in real-time. Now, with the introduction of function calls in the openai ...

Eliminating single and multiple relationships - Mongoose

My Assignment schema includes references to both Groups and Projects. Assignment == Group [One-One Relationship] Assignment == Projects [One-Many Relationship] Here is my Assignment Schema: var AssignmentSchema = new Schema({ name: String, group ...

Steps to Make a White Content Box on Top of an Image Background using HTML/CSS

I am currently struggling with overlaying a white box on top of my background image in order to have my text inside the box for a more visually appealing look. Despite trying to add CSS code like this: .white-box { position: absolute; background-c ...