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

Get Onsen UI 2 up and running without the need for Angular

Is it possible to install Onsen UI 2 without Angular? I have tried following various guides from , but when attempting the JavaScript method (> npm install onsenui) I consistently encounter a ReferenceError: angular is not defined. How can I properly ins ...

Issues with special characters in @font-face rules

For some reason, I'm encountering issues with the CSS3 property @font-face in certain browsers when trying to use my own fonts. Chrome, Safari, and IE10 work fine, but other browsers present several problems: The code I used looks like this: (fonts G ...

How to Override Certificate Expiry in JavaScript

Is there a way to bypass security for an expired certificate when making an Https post request in Javascript? I have been successful in doing this with C# and Java, but unsure about how to proceed in JavaScript. function post() { var xmlhttp; xmlhtt ...

What could be the reason for getElementsByClassName failing to work on dynamic HTML elements?

I'm currently in the process of generating multiple dynamic HTML tables and assigning a class to each one. Here's an example: var x = document.createElement("TABLE"); x.className = "table_pos_parts"; //var row = x.insertRow( ...

What causes the discrepancy in results between the quoted printable encoding operation in JavaScript and Oracle?

Programming Languages: // JavaScript code snippet //https://www.npmjs.com/package/utf8 //https://github.com/mathiasbynens/quoted-printable par_comment_qoted = quotedPrintable.encode(utf8.encode('test ąčęė')); console.log('par_comment_qot ...

Encountering a CouchDB 401 Unauthorized Error

I have a couchDB database named "guestbook". Initially, I utilized the following code to add a user to the "_users" database: $scope.submit = function(){ var url = "https://sub.iriscouch.com/_users/org.couchdb.user:" + $scope.name; console.log(url); $ht ...

onmouseleave event stops triggering after blur event

I am facing an issue with a mouseleave event. Initially, when the page loads, the mouseleave event functions correctly. However, after clicking on the searchBar (click event), and then clicking outside of it (blur event), the mouseleave functionality stops ...

Difficulty comprehending the fallback for JSON.parse in jQuery.parseJSON

Check out the origin of $.parseJSON function (data) { if (typeof data !== "string" || !data) { return null; } // Remove leading/trailing whitespace for compatibility data = jQuery.trim(data); // Try native JSON parser first ...

What is the best way to vertically align Bootstrap Columns to ensure they have consistent heights?

I'm currently in the process of building a website that features multiple images and content organized into columns using Bootstrap as the framework. I'm wondering if there's a way to automatically adjust all the columns to the height of th ...

What is the reason for the value of an object's key becoming undefined when it is set within a loop?

I've always wondered why setting a certain object's key as its own value in a loop results in undefined. Take this code block, for example: var text = 'this is my example text', obj = {}, words = text.split(' '); for (i = ...

Position an element to the right within a div using the float property

My product page features a range of attributes that can vary from 1 to 4, each sharing a common fieldset class name. I am attempting to position two of the fieldsets side by side and the remaining ones below them in a similar layout. However, achieving thi ...

Code snippet for converting the current webpage into a PDF using Jquery

Looking for guidance on how to convert the current webpage into a PDF using client-side (JQuery) code. The PDF should include all content from the webpage along with a few images if possible. The main requirement is to have all webpage content in the PDF, ...

Dynamic Element with Mousewheel Event

Simply put, I am attempting to attach a 'mousewheel' event to a div that contains a scrollbar. My code functions properly when used outside of the plugin I developed, but as soon as I convert it into a plugin, it stops working. I tested changing ...

ngSwitchCase provider not found

While following a tutorial and trying to implement what I learned, I encountered an error that I'm having trouble understanding. The browser console shows an error message stating [ERROR ->]<span *ngSwitchCase="true">, but I can't figure ...

tips for remaining in modal window post form submission

I have a form within a modal window. I am using ajax to load content in the same modal window, but the issue is that it redirects to the main page after submitting the form. How can I ensure that the modal window stays open even after the form submission? ...

Set the height of the last child element to 100% in the CSS

Seeking assistance to adjust the height of the final list item to 100% in order to match the varying height of the right-floated div. ul.menu li:last-child {height:100%} Here is an example of my current situation: http://jsfiddle.net/kvtV8/1/ Any help ...

Construct a string by combining the elements of a multi-dimensional array of children, organized into grouped

My task involves manipulating a complex, deeply nested array of nodes to create a specific query string structure. The desired format for the query string is as follows: (FULL_NAME="x" AND NOT(AGE="30" OR AGE="40" AND (ADDRESS ...

How can I display the output from Geocoder in a text box using the ArcGIS JavaScript API?

I am trying to customize the Geocoder text box in the ArcGIS JavaScript API by overriding the default search result. Although I have written some code for this purpose, I am not satisfied with the results. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 ...

Issue encountered while loading JSON data into DynamoDB's local instance

I have successfully set up DynamoDB local and everything is functioning as expected after going through their documentation. I have also tested their example code, which worked flawlessly. The Users table has been created with the name "Users". Below is ...

The error message states: "Cannot create element as the React object is not

Recently delving into the world of React and Material UI, I've been working on creating an AppBar with nested Tabs. Here's a snippet of my current approach: import {React, PropTypes, Component} from 'react'; import TodoTextInput from & ...