What is the best way to include a JavaScript variable within CSS styling?

I am currently implementing a dropdown menu system where the image of a parent div changes on mouse hover over a link, and reverts back when the mouse moves away. I have this functionality set up using a variable in my HTML code. Is there a way for me to move this variable into my CSS stylesheet and call it through an id or class?

Within the <li> tag, you can observe the mouseover and mouseout events that trigger the image change. I would like to assign a class or id to simplify calling this variable.

This is a snippet of my HTML:

<div onmouseover="changeImage(fashionSrc)" onmouseout="changeImage(fashionSrc1)">
    <h3>Casuals</h3>
</div>
<ul>
    <li onmouseover="changeImage(fashionSrc2)" onmouseout="changeImage(fashionSrc1)"><a href="#">Menu 1</a></li>
    <li onmouseover="changeImage(fashionSrc3)" onmouseout="changeImage(fashionSrc1)"><a href="#">Menu 2</a></li>
    <li onmouseover="changeImage(fashionSrc4)" onmouseout="changeImage(fashionSrc1)"><a href="#">Menu 3</a></li>
    <li onmouseover="changeImage(fashionSrc5)" onmouseout="changeImage(fashionSrc1)"><a href="#">Menu 4</a></li>
    <li onmouseover="changeImage(fashionSrc6)" onmouseout="changeImage(fashionSrc1)"><a href="#">Menu 5</a></li>
    <li onmouseover="changeImage(fashionSrc7)" onmouseout="changeImage(fashionSrc1)"><a href="#">Menu 6</a></li>
</ul>

Answer №1

onMouseOver = "this.src="../your_unique_path/image1.png"; //or something different
onMouseOut = "this.src="../your_unique_path/image2.png"; //or something different

Explore the concept of unobtrusive javascript, link 1 link 2

Answer №2

Is there a method to incorporate this variable into my CSS stylesheet and then reference it using an id or class?

As far as I know, there is no direct way to achieve this. However, you can modify the element's class and define those in your CSS instead. It would be advisable to utilize the :hover pseudo-class rather than resorting to JavaScript tricks in this scenario.

Answer №3

Learn how to easily create a drop-down menu with this quick tutorial.

Start by writing the HTML code:

<div class="menu">
  <h2></h2>
  <ul>
    <li>Menu Item 1</li>
    ...
  </ul>
</div>

Add some CSS for styling:

.menu {
  position:relative;
  height:40px;
}

.menu h2 {
  /* Add your heading styles here */
}

.menu ul {
  display:none;
  position:absolute;
  top:40px; /* Should match the menu's height */
  left:0;
}

/* Show the submenu on hover */
.menu:hover ul {
  display:block;
}

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

Typescript conversion: Changing a relational array into a tree object

My database is structured as an array of objects with the following format; array = [ {"name": "a", "id": "1", "parentId": NULL}, {"name": "b", "id": "2", "parentId": "1"}, {"name": "c", "id": "3", "parentId": "1"}, {"name": "d", "id": "4", "parentId" ...

CSS - tackling the issue of menu items overlapping

My menu has two items, and when the user clicks on each item, a sub-menu is displayed. The issue is that both menus are displaying at the same spot - under the first item. I've tried tweaking it for a while but can't seem to fix the problem. Ad ...

Tips for effectively handling the auth middleware in react.js by utilizing LocalStorage

After making a call to the authentication API, the plan is to save the authentication token in LocalStorage and then redirect to a dashboard that requires token validation for entry. However, an issue arises where the authentication token isn't immedi ...

Checking for the Existence of a Database Table in HTML5 Local Storage

Upon each visit to my page, I automatically generate a few local database tables if they do not already exist. Subsequently, I retrieve records from the Actual Database and insert them into these newly created local tables. I am wondering if there is a me ...

Explore an array of objects to find and retrieve a value from the final matching object in JavaScript

I'm having difficulty retrieving the value for the last event that includes "SearchResults" in the scenario outlined below: Here is a schema of my datalayer where I am looking to gather information. Currently, I have managed to write the following co ...

Is it time to advance to the next input field when reaching the maxLength?

In my Vue form, I have designed a combined input field for entering a phone number for styling purposes. The issue I am facing is that the user needs to press the tab key to move to the next input field of the phone number. Is there a way to automaticall ...

Create an Android application using Node.js

While developing my mobile application, I am utilizing html5 with node.js to create a chat box for users connected on the same wireless network. However, I encounter an issue when coding on my desktop using node.js software. How can I overcome this challen ...

What methods can I use to enable web browsers to remember form field data that is not transmitted in the usual manner?

The code provided here is almost perfect in terms of functionality. function post_form() { http=new XMLHttpRequest(); http.onreadystatechange=function() { if (http.readyState==4 && http.status==200) some_div.innerHTML=http.responseText; ...

The Clash of Form Action and JavaScript

Can someone help me with this issue? I have a form and a script to trigger an alert message. The code I'm using is working well: <input id="autocomplete" class="input_message" type="text" name="message" autocomplete="off" placeholder="...typ ...

Conceal an entire div using CSS, especially if a portion of it remains unoccupied

Is there a way to conceal an entire division if a part of it is void? For instance, if "dd" is empty as indicated below, can I hide the entire class "test" so that the keyword Restrictions does not display either? I attempted .test dd:empty { display: none ...

What is the best approach to perform a search in mongoose based on specific query parameters?

I have a form that allows users to search for transactions by specifying the buyer name, item name, or both. This means I can receive any of these queries: localhost:8000/allPayments/?i=pasta localhost:8000/allPayments/?b=Youssef localhost:8000/ ...

Is there a way for me to prevent a particular file from being cached by web browsers?

Is there a way to prevent Web Browsers from caching a particular file? For example: <img src="myImage.jpg" cache="false"></img> If possible, how can this be achieved? The code <meta http-equiv="cache-control" content="no-cache" /> ins ...

What are the steps for incorporating a linear-gradient hue into a Slider?

Is it possible to apply a linear-gradient as color to Material-UI Slider? I have tried everything but can't seem to make it work. color: 'linear-gradient(180deg, #29ABE2 0%, #00EAA6 100%)' ...

When attempting to toggle the view on button click, it is not possible to select a shadowRoot

I am facing an issue with my parent component named ha-config-user-picker.js and its child component called edit-user-view.js. Parent Component: It contains a mapping of users and includes the child component tag along with its props. When a click event i ...

Do not use npm to install underscore libraries

How can I resolve the error I encountered while attempting to install packages using npm? Here is my packages file: "dependencies": { "express": "~3.3.6", "socket.io": "0.9.16", "jade": "~0.35.0", "less-middleware": "~0.1.12", "redis ...

When using the onclick function, an unexpected behavior occurs where instead of displaying content, the page

Below is a summarized version of my code: HTML <a onclick="showHideDiv('bio')" target='_self'> bio <div id="bio" class="shadowScreen" style="display: none;"> <p class="showBio"> Bio! </p> &l ...

Warning: The class name hydration discrepancy between server and client (Caution: Property `className` does not correspond between the Server and the Client)

Trying to figure out if my problem is a stubborn bug, a support issue, or just a configuration mismatch has been quite the journey. I've spent so much time on this, not exactly thrilled to be reaching out for help. After searching for 3 days and only ...

Handling a JSON array error when working with a JSON string field

Attempting to create a JSONArray object with nested arrays and json strings, specifically looking at the "res" field. [{ "time": 123813213, "value": [{ "name": "task", "res": "{\"taskName\" : \"NAME\", \"ta ...

When using HLS with Media Source Extensions on mobile devices, the <video> element with the muted and autoplay attributes may freeze on the first frame

I recently added a background video to our website using mux.com. The video is set to autoplay with HLS, but Chrome requires Media Source Extensions for playback. To ensure the HTML5 video auto plays, I included the necessary mute parameters as well. How ...

React Intersection Observer Triggering Memory Leaks

Issue Description: I encountered a problem with my React app crashing on mobile. The Chrome dev tools revealed that garbage collection wasn't triggering, and upon inspecting the heap, I found that the top constructors by retained size were all linked ...