Enhance User Experience by Implementing Event Listeners for Changing Link Visibility Using mouseover and getElementsBy

I am new to JavaScript and struggling to find a solution.

Despite searching online for fixes, none of the solutions I've found seem to work for me. I have spent hours troubleshooting the issue but I must be missing something crucial. Can someone please help?

CSS: I have created a basic two-column div (out of 12 columns) with a CSS transition that increases its width from 2% to 15% on hover.

HTML: Inside the div, I have added some test links which are currently hidden using a CSS class.

JS: My goal is to use JavaScript to make these links visible when the mouse hovers over the div.

HTML:

<div id="linkpopout" class="col-2 popout">
  <a href="www.bing.com" class="menulinks">Bing</a>
  <a href="www.yahoo.com" class="menulinks">Yahoo</a>
  <a href="www.google.com" class="menulinks">Google</a>      
</div>

CSS:

.col-2 {width: 16.66%;}

.popout {
  background:lightblue;
  transition:width 0.5s, height 0.5s;
  transition-timing-function:ease-out;
  width:2%;
  height:300px;
  float:left;
}

.popout:hover {
  width:15%;
  height:300px;
}

.menulinks {
  visibility:hidden;
}

JS:

var linkpop = document.getElementById("linkpopout");
var popoutlinks = document.getElementsByClassName("menulinks");
linkpop.addEventListener("mouseover", makeVisible);
function makeVisible() {
  popoutlinks.style.visibility="visible";
}

In addition to trying

document.getElementsByClassName(menulinks").style.visibility="visible";
I also attempted to use opacity instead of visibility, but it had no effect.

Thank you.

Answer №1

Avoid the use of JavaScript.

.col-2 {width: 16.66%;}

.popout {
  background:lightblue;
  transition:width 0.5s, height 0.5s;
  transition-timing-function:ease-out;
  width:2%;
  height:300px;
  float:left;
}

.popout:hover {
  width:15%;
  height:300px;
}

.menulinks {
  visibility:hidden;
}

.popout:hover .menulinks {
  visibility: visible;
}
<div id="linkpopout" class="col-2 popout">
  <a href="www.bing.com" class="menulinks">Bing</a>
  <a href="www.yahoo.com" class="menulinks">Yahoo</a>
  <a href="www.google.com" class="menulinks">Google</a>      
</div>

Answer №2

If you'd like to change the visibility of links based on whether the menu is displayed or not, here's how you can achieve that:

JavaScript:

<script>
var linkpop = document.getElementById("linkpopout");
var popoutlinks = document.getElementsByClassName("menulinks");
linkpop.addEventListener("mouseover", makeVisible);
linkpop.addEventListener("mouseout", makeVisible);

function makeVisible() {
  for (let i = 0; i < popoutlinks.length; i++) {
    popoutlinks[i].classList.toggle("vis");
  }
}
</script>

The 'toggle' method in 'classList' linked to an element will either add or remove the specified class from the element based on its current state. If the class exists, it will be removed; otherwise, it will be added. This method is particularly useful for menus that pop out like this one. The script loops through all elements, such as your menulinks, and toggles the class individually.

Create a class to toggle on and off with the default state corresponding to the class you desire for the element.

CSS:

.menulinks { visibility:hidden; }
.vis { visibility:visible }

Answer №3

To iterate through the elements in the DOM:

getElementsByClassName

This method retrieves an array-like object containing all child elements with specified class names. When used on the document object, it searches the entire document, including the root node. It can also be called on any element to fetch only elements that are descendants of the specified root element and have the given class names.

function makeVisible() {
  popoutlinks.forEach(function(e) {
      e.style.visibility="visible";
  });   
}

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

Find the height of the viewport using jQuery, subtracting (n) pixels

Apologies if the topic seems puzzling, I couldn't find a better way to explain it. I utilized jQuery to adjust the height of a div to match the size of the viewport. var slidevh = function() { var bheight = $(window).height(); $(".container" ...

What is the best way to retrieve the nearest form data with jQuery after a child input has been modified?

I have a page with multiple forms, each containing several input checkboxes. When one of the form inputs changes, I want to gather all the parent form's data into a JSON array so that I can post it elsewhere. I'm having trouble putting the post ...

Failure in Retrieving Fresh Information via Ajax Call

My web application utilizes polling to constantly update the status of a music player. To achieve this, I have implemented a method using setInterval to execute an Ajax call every half second. This setup functions as intended on a variety of browsers inclu ...

Warning: Unhandled promise rejection - The type error occurred because the property 'close' of the object is undefined

I am currently configuring node.js in order to test my JavaScript codes using the Jest JavaScript testing framework. Can anyone spot what I might have done incorrectly? package.json file { "name": "institute-jest", "version&quo ...

Difficulty paginating jqgrid when using an array as the data source

Encountering an issue with pagination in jqgrid while working with array data containing 18 records. Even after specifying pagination:true, pager:jQuery('#pager1'), the records are not displaying in pages. Can anyone assist me in implementing pag ...

Converting a Base64 URL to an image object: A step-by-step guide

I currently have a base64 URL in the following format: data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEAYABgAA My objective is to convert this into an image file with the following properties: [File] 0: File lastModified: 1559126658701 lastModifiedDate: Wed M ...

Tips for deleting a CSS class from a Wicket element

If you're looking to dynamically update a CSS class of a component in Java code, one way to do so is by using an AttributeAppender: component.add(new AttributeAppender("class", true, new Model<String>("foo"), " ")); You can also utilize a util ...

The NodeJS req.query is providing inaccurate information

When I send a JSON from the Client-Side to a NodeJS Server, it looks like this: $.ajax({ type: "POST", dataType: "jsonp", url: "www.xyz.com/save", data: { designation: "Software Developer", skills: [ "", "ASP.NET", "P ...

Unable to access an element using jquery

This is an example of an HTML file: <div id ="main"> </div> Here is the JavaScript code: //creating a new div element var divElem = $('<div class="divText"></div>'); //creating an input element inside the div var i ...

What is causing this code to run immediately upon the addition of Promise logic?

The coding scenario written below was supposed to have two 4-second delays. However, when the code is run, it executes immediately. It seems that there might be a lack of understanding on my part regarding some basic concept, or perhaps there's a hidd ...

Steps for incorporating events on Jquery UI button

I have a question about utilizing Jquery UI for the first time. After successfully adding a button using Jquery UI, I am now interested in adding events for when a radio switch is turned on and off. When the radiobox is switched on, I want an alert window ...

How can I leverage Express, AngularJS, and Socket.io to facilitate broadcasting and receiving notifications?

A new notification system is in the works. To illustrate, User 1 is initiating a friend request to User 2. The technologies being utilized include express.js, angularjs, and socket.io. When User1 clicks the button, a request is sent. On User2's end, a ...

JQuery Templates - when recursion becomes overwhelming

Utilizing jquery templates to create a tree structure for showcasing sections and items in a treeview format. The data layout is structured as follows, with each section containing items and subsections, while each item can potentially have additional sub ...

CSS media query that prioritizes styling for large screens over small screens

I am currently working on making my new website development project mobile responsive, but I am encountering some strange behavior that is quite frustrating. I am hoping someone can help me figure out what mistake I may be making here. Whenever I test the ...

What is the best way to showcase the chosen items from a treeview in ReactJS?

I'm struggling to figure out how to showcase the selected elements from my treeview. Any ideas or tips? The main purpose of this treeview is to filter data for export purposes. You can find the original code here. import React, {useEffect, useState} ...

Limiting the DatePicker in React JS to only display the current year: Tips and Tricks!

I'm currently implementing the KeyboardDatePicker component in my React application to allow users to choose a travel date. However, I am looking to restrict the date selection to only the current year. This means that users should not be able to pick ...

Automatically trigger the Submit button click with this selector

I'm having trouble automating the clicking of a 'Submit' button that only becomes clickable after a specific action is taken. In this case, the user needs to click the TOS checkbox before the button can be clicked. I've been unable to f ...

Compiling modal window content in AngularJS can lead to the creation of controllers that are left disconnected

I implemented a modal window triggered by fancybox in my project. Once the modal is displayed, fancybox triggers a "modalShown" event that is listened for by AppController. In this listener, $compile is called on the modal content to create the ModalContro ...

Having trouble configuring and executing Vue.js within Laravel

I am fairly new to vue.js but I have experience with laravel. With the recent release of laravel 5.3, I decided to try running a sample application using Vue. resources/js/app.js : /** * First we will load all JavaScript dependencies for this pr ...

The issue of JQuery Mobile not recognizing HREF links when combined with Javascript

I am facing a challenge with my button functionality that is supposed to open a panel. However, there seems to be an interference caused by my JavaScript code. The panel contains a notifications center and in order to retrieve the notifications, I have to ...