Modifying the visibility CSS property through the DOM on mouseover: A quick guide

After creating an <img/> element using JavaScript, I am trying to make it appear only when the user hovers over it.
Although the callback function makesVisible() is being called, nothing seems to change.

My goal is to switch the visibility property from hidden to visible

var imgHover = document.createElement('img');
        imgHover.setAttribute("src", "img/icona_play.jpg");
        imgHover.style.width = "30px";
        imgHover.style.height = "23px";
        imgHover.style.position = "absolute";
        imgHover.style.margin = "0 auto";
        imgHover.style.left = "45px";
        imgHover.style.bottom = "35px";
        //I want to change this following property
        imgHover.style.visibility = "hidden";
        imgContainer.appendChild(imgHover);

        //Calling the function when mouseover
        imgContainer.addEventListener("mouseover", makeVisible, false);


        function makeVisible()
        {
            imgHover.style.visibility = "visible";
        }

Answer №1

One alternative is to utilize the opacity property. Start by initializing it like this: imgHover.style.opacity = 0; Then, in the makeVisible function, update it to imgHover.style.opacity = 1;

Another approach to address this issue is by attaching the addEventListener method to the parent div. Assuming there is a container surrounding the image with identical dimensions.

For instance:

imgContainer.addEventListener("mouseover", makeVisible, false);

The key difference between opacity and visibility is that both maintain the element's space on the page. However, a hidden element will not respond to mouse or pointer events.

Answer №2

Your code is functioning correctly, but it is important to ensure that you have a valid reference to imgContainer and a valid path to an image for the dynamically created element:

var imgContainer = document.getElementById("container");
var imgHover = document.createElement('img');
imgHover.setAttribute("src", "https://www.wpclipart.com/signs_symbol/arrows/button_arrows/play_buttons/play_button_gray.png");
imgHover.style.width = "30px";
imgHover.style.height = "23px";
imgHover.style.position = "absolute";
imgHover.style.margin = "0 auto";
imgHover.style.left = "45px";
imgHover.style.bottom = "35px";
imgHover.style.visibility = "hidden";
imgContainer.appendChild(imgHover);

imgContainer.addEventListener("mouseover", makeVisible, false);

function makeVisible(){
  imgHover.style.visibility = "visible";
}
<div id="container">Hover Over Me</div>

It is recommended to avoid inline styles on elements as they can be difficult to override and lead to code duplication. Using CSS classes and the element.classList API simplifies styling.

The use of the visibility property affects whether an element is seen or not, but it still occupies space in the UI. In most cases, utilizing display:none to hide elements and then removing this instruction to show them is preferred.

Furthermore, instead of using setAttribute(), directly configuring element properties simplifies the code. Most HTML attributes correspond to JavaScript object properties, making manipulation easier.

Here is a consolidated example incorporating these suggestions:

var imgContainer = document.getElementById("container");
var imgHover = document.createElement('img');

// Set element properties directly:
imgHover.src ="https://www.wpclipart.com/signs_symbol/arrows/button_arrows/play_buttons/play_button_gray.png";

// Add pre-made classes to style the element
imgHover.classList.add("hoverImg");
imgHover.classList.add("hidden");

imgContainer.appendChild(imgHover);
imgContainer.addEventListener("mouseover", makeVisible);
function makeVisible(){
  imgHover.classList.remove("hidden");;
}
.hidden { display:none; } /* Used when an element needs to be hidden */

/* Applied via JS */
.hoverImg {
  width:30px;
  height:23px;
  position: absolute;
  margin:0 auto;
  left:45px;
  bottom:35px;
}
<div id="container">Hover Over Me</div>

Answer №3

When adding elements to the imgContainer, ensure you re-fetch the element reference in the makeVisible() function. This will prevent any changes to the original element. Use document.querySelector("img") to retrieve the appropriate 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

Maintain font kerning for span elements that are not displayed inline

I am looking to add some transform effects to individual letters in a word. To achieve this, I have enclosed each letter within a span element. However, when setting the display of these spans to inline-block, the font kerning gets disrupted. I have exper ...

Retrieving data from an HTML input tag and storing it in a variable

I'm currently working on a project that involves reading the contents of an uploaded file through an input tag and storing it in a variable. My goal is to then use an algorithm to decrypt the .txt file: <input type="button" value="decrypt" id="dec ...

Extract the String data from a JSON file

valeurs_d = ""; for (var i = 0; i < keys.length -1 ; i++) valeurs_d += + event[keys[i]] + ", "; var str5 = ","; var str6 = str5.concat(valeurs_d); var valeurs = str6.sub ...

CSS Text-Align failing to align elements

As a newcomer to CSS, I am seeking assistance with aligning items on a webpage. Essentially, I am trying to achieve an alignment that resembles the following: Item 1 ...

Methods for Expanding a Div within an Oversized Row, Despite Height Constraints

I have a situation where I need to adjust the height of a cell in a table. One of the cells contains a larger element that causes the row to expand vertically. I also have another cell with a div element set to 100% of the cell's height. However, I wa ...

What is the best method for creating a 10-page PHP form that contains more than 100 input fields in an efficient manner?

I am currently in the process of constructing a substantial PHP form that will extend over 10 pages and contain well over 100 input fields. Each input will be stored in a database. I am starting to encounter challenges keeping track of all the variables as ...

What is the best way to clear the selected option in a dropdown menu when choosing a new field element?

html <div class="row-fluid together"> <div class="span3"> <p> <label for="typeofmailerradio1" class="radio"><input type="radio" id="typeofmailerradio1" name="typeofmailerradio" value="Postcards" />Postcards& ...

Adding a scroll bar to a fixed container: tips and tricks

I am looking to implement a scrollbar in a fixed container for the cart products. The goal is to enable easy navigation through a large number of products added to the cart by scrolling within the container. Below is the HTML code snippet representing the ...

What is the best way to include an API key in the response to an Angular client application?

I'm working on transferring my API key from NodeJS to an Angular client application using $http, but I am unclear on the approach. Below is a snippet from my NodeJS file: // http://api.openweathermap.org/data/2.5/weather var express = require(' ...

discovering identical patterns within a collection of elements

Attempting to identify matching patterns for the string input by the user in a textbox. The code works well in most cases, but there are instances where it does not provide all the required results. Below is a link to a jsfiddle displaying the functioning ...

Is it possible to obtain a reference to the object with _.find? What is the correct way to update a property of the resultant object

When using lodash find to query an object from an array and then setting a property of that object, the array remains unchanged when printed out. I would appreciate feedback from someone with more experience in handling objects with lodash in JavaScript. ...

Ways to resolve the issue of my sidebar displaying at the bottom of the page on smaller screens

Below is the code snippet that generates a Bootstrap page with lorem text and a sidebar. The issue I am facing is that when the browser window size gets smaller, the sidebar appears at the bottom instead of the side. On very small resolutions, it becomes h ...

Trouble Loading HTML Template Post Email Dispatch in Django

In my Django project, I have set up functionality to send an email after a form submission using the smtplib module. The email is sent successfully, but for some reason, I'm encountering an issue where the corresponding HTML template (delivery_email_s ...

"Troubleshooting: Unable to make a successful Jquery ajax call

I am encountering an issue with my file directory, where I have two files present: js/form-validation-reg.js and HTML/registeruser.php. The JavaScript file is responsible for validating a form from another HTML file. Although I have confirmed that all the ...

Divide a string into various text boxes

Is there a way to allow users to edit the value of a field that is Vertex 3D? The stored value is in string format, but I want to present it to the user as three separate input fields for easier editing. I am looking for a method to split the string by sp ...

Is it possible to create an image or logo that moves in sync with the user's scrolling

Having trouble articulating this question, but I'm trying to replicate the logo in the top right corner of this website: I want the logo to move along with the user as they scroll down, remaining visible at all times. Any ideas on how to achieve this ...

Addressing the issue of empty ngRepeat loops

Utilizing ngRepeat to generate table rows: <tr ng-repeat="User in ReportModel.report" on-finish-render> <td><span>{{User.name}}</span></td> </tr> An on-finish-render directive triggers an event upon completion of t ...

I aim to arrange three div elements in a single row with varying widths - placing one on the left, another in the center, and the last

I am trying to have three div elements in one row with different widths - one on the left, one in the center and one on the right. The left div should be 160px The center div should be 640px The right div should be 160px My goal is for them to appear se ...

What steps should I take to ensure that the JSON data is exclusively accessible to my JavaScript code?

Creating a web application that requires visualizing a significant amount of data using Charts. Discovered some interesting javascript libraries [dynagraph] that can handle this task. However, encountering an issue with using javascript to access data in J ...

What is the best way to implement form validation using HTML in the front end of Google Apps Script?

I've written a function to validate user inputs in an HTML form (it's a sidebar on Google Sheets): Credit to Chicago Computers Classes function validate() { var fieldsToValidate = document.querySelectorAll("#userform input, #userform se ...