How to merge multiple hover effects using JS or JQuery


I am just beginning my journey as a web designer and currently delving into the world of JavaScript for enhancing website functionality. While working on my latest project, I encountered a challenge. I wanted to create a menu where specific elements would be highlighted on hover and click.

function hoverAndActive(firstElement, secondElement){
$(firstElement, secondElement).hover(function(){
        $(firstElement, secondElement).toggleClass("hoverMenu");
    }).mousedown(function(){
        $(firstElement, secondElement).addClass("activeMenu");
    }).mouseup(function(){
        $(firstElement, secondElement).removeClass("activeMenu");
    }).mouseleave(function(){
        $(firstElement, secondElement).removeClass("activeMenu")
    });
}

hoverAndActive("#home","#hometext");
hoverAndActive("#bio","#biotext");
hoverAndActive("#contact","#contacttext");

I am trying to streamline the hover and mouseclick functionality for each menu item. Although I managed to achieve this by duplicating code in the function, I'm looking for a way to write the functionality once and simply input the IDs for each menu item. I prefer using JS over CSS as each pair of IDs is located in very different sections of the html.

Appreciate your assistance :)
Asger Kjeldsen



Edit: Added # to the functions. Clarification



Edit: adding HTML:

<div id="navigation">
    <div id="menu">
        <a href="#BodyHead"><div id="home" class="button"><img src="img/home.png"></div></a>
        <a href="#Test"><div id="bio" class="button"><img src="img/bio.png"></div></a>
        <a href="#"><div id="contact" class="button"><img src="img/contact.png"></div></a>
    </div>
    <div id="menutext">
        <a href="#BodyHead"><div id="hometext" class="button"><p>HJEM</p></div></a>
        <a href="#Test"><div id="biotext" class="button"><p>BIOGRAFI</p></div></a>
        <a href="#"><div id="contacttext" class="button"><p>KONTAKT</p></div></a>
    </div>
</div>

Answer №1

When using the syntax $(firstElement, secondElement), only the firstElement is selected within the context of secondElement. This is essentially the same as using

$(secondElement).find(firstElement)
.

To combine multiple selectors, you must place them in a single string separated by commas.

function handleMouseEvents(firstElement, secondElement){
    var selectedElements = $(firstElement + ',' + secondElement);
    selectedElements.hover(function(){
        selectedElements.toggleClass("hoverEffect");
    }).mousedown(function(){
        selectedElements.addClass("activeEffect");
    }).mouseup(function(){
        selectedElements.removeClass("activeEffect");
    }).mouseleave(function(){
        selectedElements.removeClass("activeEffect")
    });
}

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

Is there a way to transform a string property into a custom type in a TypeScript array?

I am faced with a situation where I have an interface that is extending a MongoDB document, along with some sample data that is also extending that interface. Below is an outline of the interface: export default interface IModel extends Document { _id: Obj ...

Tips for incorporating a set offset while utilizing the scrollTop() function

I have successfully implemented a code that sets a position:fixed to a div when it scrolls past the top of the screen. The code I used is as follows: var $window = $(window), $stickyEl = $('#the-sticky-div'), elTop = $stickyEl.o ...

Navigating dropdown list items using the keyboard in TypeScript is a breeze

I've encountered a bug while working on my open-source project. The issue is with navigating the dropdown list items using the keyboard (arrow key/tab). I have implemented the keyboard-navigation logic, but I'm unsure of how to make it work corre ...

What is the most efficient way to transfer form data from one JSP page to another?

I need to transfer information from one webpage (1.jsp) to another webpage (2.jsp). The data that needs to be transferred includes checkboxes, radio buttons, and drop downs. This data will be used in 2.jsp to generate the appropriate page. Is there a way ...

How can I search for a particular string in JavaScript?

I have a unique custom div that has been modified to function as an input element. Inside this custom div input element, there is a <p> tag with a default placeholder text. My goal is to verify whether the content of this div is empty or contains new ...

Conceal the current table and reveal a new table upon clicking using jQuery

Within my form, there is an option to select a specific type. Depending on the chosen type, relevant data is displayed in a table. Upon selecting the first type and clicking the submit button, the data is correctly shown in the table. However, when selec ...

Using Selenium with Python to interact with dropdown elements in webpages

My goal is to extract data from using python's selenium library. I've encountered an issue with two interconnected elements. There are two select statements: a) with id="promptCategoryInput" and b) id='promptShareInput'. The manual pro ...

Creating the data type for the input file's state: React with Typescript

Encountering an error when attempting to define the type of a file object within state: Argument of type 'null' is not assignable to parameter of type 'File | (()=> File)'.ts. Currently working on an upload component that allows for ...

Initiate node and PM2 application using a batch file

Currently, I have a chat-bot application running on Node.js, which I always keep active using pm2. I am looking to streamline the process of launching the application. Instead of having to run the start command from the console every time, I would like to ...

Is it possible to utilize RedisJson to store express-session data in place of Redis?

I am currently attempting to access the express-session data manually without relying on req.session.reload() and req.session.save(). My aim is to utilize Redisjson instead of the default redis. The problem I am encountering is that the express-session set ...

What is the best way to select an element with a dynamic ID in jQuery?

I'm encountering an issue when passing the ID through a directive. I'm unable to access the element using jQuery within the Link function, even though the element is receiving the correct dynamic ID as a parameter: Here's the Directive: (f ...

`Incompatibility with Internet Explorer causes AJAX loader GIF to fail when using asynchronous POST requests`

Is there a way to display an AJAX loader gif during an asynchronous POST request on Internet Explorer? It seems that the request process stalls and the updated content is not visible when using Internet Explorer. However, everything works fine on browser ...

Is the presence of the selenium webdriver being registered?

Is there a method to detect if a website can tell I am using a bot while running Selenium WebDriver in Python or Puppeteer in JavaScript? Are there any resources that indicate whether a bot test would be failed, such as Cloudflare or Captcha? Appreciate a ...

Tips for personalizing an angular-powered kendo notification component by adding a close button and setting a timer for automatic hiding

I am looking to enhance the angular-based kendo notification element by adding an auto-hiding feature and a close button. Here is what I have attempted so far: app-custom-toast.ts: it's a generic toast component. import { ChangeDetectorRef, Componen ...

Utilizing jquery-confirm for Efficiently Redirecting Links in a Web Browser

I recently started using the jquery-confirm v3.0.3 plugin (available at ) to confirm various actions on my website. However, after implementing the code below, I noticed that the action specified in the link's href attribute is not being executed whe ...

Django base .js file causing JQuery compatibility issues

In my Django base template, I am utilizing app.js within a theme. I now need to implement a modal popup using AJAX, which requires calling a jQuery function. The error below occurs when trying to call the page where the modal popup button is located, which ...

What could be the reason for the modal-side modal-top-right class not functioning properly in Bootstrap modals

Here is the code snippet: <div class="modal fade right" id="basicModal" tabindex="-1" role="dialog" aria-labelledby="basicModal" aria-hidden="true"> <div class="modal-dialog modal-side modal-bottom-right"> <div class="modal-content"&g ...

PHP jQuery buttons for popovers

With a simple click of a button, I can generate 8 presentations and then edit each one individually by clicking on its respective name. Within this editing process, there is another form where I would like to include additional buttons that allow me to cus ...

What is the best way to implement this design using CSS flexbox?

I'm working on designing a simple layout that looks like this: https://i.stack.imgur.com/oCzyV.png Currently, I have the following HTML structure with some variations in class names and additional markup within each element: <div class="site ...

Leveraging external data for testing in Protractor script

I am encountering an issue while attempting to access test data using JSON, as it keeps showing up as undefined. I am implementing a Page Object Model and trying to reference external test data. However, when passing the values from my test data into a fun ...