Switching the visibility of a DIV by clicking on a list item

Struggling with a seemingly simple function for way too long now. The task is to show a hidden div with information on an item when it's clicked, without using jQuery. Tried multiple examples from various sources but nothing seems to work. Hoping for a straightforward solution before going crazy. Any suggestions?

JS:

var div = document.getElementById('show')
var beer = document.getElementById('beer')

function show_div() {
    if (div.style.display == "none") {
        div.style.display = ""
    } else {
        div.style.display = "none"
    }
};

CSS

div { display: none; }

HTML

<li>Beers I Currently Have
    <ul>
        <li><a href="#" id="beer" onclick="show_div">2 Sierra Nevada Bigfoot (12/11/14)</a></li>
    <div id="show">Delicious barley wine that has been aging in my cellar for nearly 2 years now.</div>
    ....

Answer №1

HTML:

<ul>
    <li>
        <a href="#" id="beer">2 Sierra Nevada Bigfoot (12/11/13)</a>
        <div hidden>Delicious barley wine that has been aging in my cellar for nearly 2 years now.</div>
    </li>
</ul>

CSS:

/* No need to set display:none here
   since we are using 'hidden' directly
   in the element. */
#beer div { }

JavaScript:

var beer = document.getElementById('beer')

// Add an event listener to beer. Listen for
// the 'click' event.
beer.addEventListener('click', function(e) {
    e.preventDefault(); // prevent default <a> behavior

    info = e.target.nextElementSibling;
    if (info.hidden) info.hidden = false;
    else info.hidden = true;

    return false; // prevent default <a> behavior
});

This code allows users to toggle a hidden div by clicking on a link within a list item. Placing them next to each other in the DOM makes accessing the div easier. The e.target.nextElementSibling method is used to access the next sibling element of the clicked link. To understand what e represents, use console.log(e) in the click handler. Check out this fiddle for a live demo: https://jsfiddle.net/zs6aL7x2/

Answer №2

  • When using onclick="show_div", remember to include parentheses like this: onclick="show_div()"
    • To display an element with id #show, use CSS rule div #show{ display: auto; } instead of div { display: none; }
    • Always remember to end each statement in your code with ;

var div = document.getElementById('show');
    var beer = document.getElementById('beer');

    function show_div() {
    if(div.style.display == "none"){
    div.style.display = "";
    } else { div.style.display = "none";
    }
    };
#show { display: auto; }
<li>Beers I Currently Have
<ul>
    <li><a href="#" id="beer" onclick="show_div()">2 Sierra Nevada Bigfoot (12/11/14)</a></li>
        <div id="show">Delicious barley wine that has been aging in my cellar for nearly 2 years now.</div>

Instead of using div.style.display which may be overridden by inline styles, consider using getComputedStyle function

Here's another approach utilizing the getComputedStyle function:

var div = document.getElementById('show');
    var beer = document.getElementById('beer');

    function show_div() {
    console.log(div.style.display);
    if(getComputedStyle(div,null).display== "none"){
    div.style.display = "block";
    } else { div.style.display = "none";
    }
    };
#show { display: none; }
<li>Beers I Currently Have
<ul>
    <li><a href="#" id="beer" onclick="show_div()">2 Sierra Nevada Bigfoot (12/11/14)</a></li>
        <div id="show">Delicious barley wine that has been aging in my cellar for nearly 2 years now.</div>

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

What is the best way to align elements in relation to a central div container?

Is there a way to align two buttons in the center on the same line, and then position a selector to the right of those centered buttons? How can I achieve this arrangement? Essentially, how do you position an element in relation to a centered div? UPDATE: ...

Operate on Nested JSON Arrays

I have the following JSON array: var salesData = [ { "products": "Cars", "solddate" : "2022-01-01", "noofitems" : " ...

Tips on converting HTML code into a data image URI

My question may seem unconventional, but here is what I am trying to accomplish. I want to create a design similar to the one found at the following link: I would like to embed text with an image and retrieve the data image URL using Ajax. I know how to g ...

Trouble with jQuery on click function, no actions triggered

I am having trouble with this jQuery function that is supposed to post the value of a variable to a PHP page and display it in the correct status class. I have included the necessary jQuery file, but for some reason, nothing is happening. Any assistance w ...

How can I align the content within two div elements?

I'm facing a bit of a challenge that I can't seem to figure out. Within a div, I have one photo and inside another div, there is also a photo. I was able to resize both images from the parent and child divs successfully. <div style="width:100 ...

Struggling to implement Datatables row grouping using ajax is proving to be quite challenging

Is there a way to group rows in a table based on date ranges, using the data from the first column ("Due_Date"), and leveraging the rowGroup extension provided by Datatables? I've tried various solutions found online, such as using the data property ( ...

The array used within the useEffect hook and the getCoordinates function appears to be distinct when printed with console

Utilizing GoogleMap API for Custom Location Display I have an imported array of JSON objects named data which includes an address property. The Google Maps API is used to retrieve coordinates from the addresses in order to generate custom markers displaye ...

How can I utilize the mapping function on a promise received from fetch and display it on the page using React

As I'm using fetch to return a promise, everything is working fine. However, I am facing an issue while trying to map over the fetched data. When I check my console log, it shows "undefined." const dataPromise = fetch('http://api.tvmaze.com/sche ...

Issue with font icons not displaying properly on Firefox

In Firefox, the icon is not displaying in the center, but it works fine in Opera. body { height: 100vh; display: grid; place-items: center; } .link { background-color: red; padding: 3px; display: grid; place-items: center; ...

Encountering Internal Server Error when running Node-Express app on render.com with query parameters live

Currently, I am facing an issue while attempting to execute a live route with query using my nodejs express application on render.com. Strangely, all other routes connected to the crud operations are functioning properly except for the search filter route ...

Searching for 10 random data records within a collection of 100 in MongoDB

Can MongoDB retrieve a specific number of random documents in one query? For example, I currently load all the documents in the collection on the JavaScript side, which is inefficient. I'm wondering if there's a better way to achieve this with a ...

Tips for customizing a bootstrap CSS file or incorporating it into your project

Embarking on a new journey into web development, I found myself diving deep into the realms of the internet to edit a template for a forum website. It's certainly a challenge, given my limited experience in this field. The template utilizes a bootstr ...

Steps to remove a specific child element using jQuery:

CSS: <h1><br style="clear:both;"></h1> I am currently working on a project that involves using the Wikipedia API. One issue I've run into is cleaning up the raw HTML output from Wikipedia, specifically dealing with removing a speci ...

Having trouble resolving errors encountered while running the `npm run build` command, not sure of the steps to rectify

I am currently working on my first app and attempting to deploy it for the first time. However, I have encountered an error that I am unsure of how to resolve. When running "npm run build", I receive the following: PS C:\Users\julyj\Desktop& ...

What is the process for retrieving values from an ajax request?

One issue I am facing is the inability to extract data from an AJAX call, where the JSON data is structured as follows: https://i.sstatic.net/UvpnI.png request I need to retrieve the value from ReviewPoint and then perform some jQuery manipulation in th ...

Tips for managing errors in HTTP observables

I'm currently facing a challenge with handling HTTP errors in an Angular2 observable. Here's what I have so far: getContextAddress() : Observable<string[]> { return this.http.get(this.patientContextProviderURL) .map((re ...

I need help converting the "this week" button to a dropdown menu. Can someone assist me in troubleshooting what I am missing?

Seeking assistance with customizing the "this week" button on the free admin dashboard template provided by Bootstrap 4. Looking to turn it into a dropdown feature but unable to achieve success after two days of research and watching tutorials. See code sn ...

What are the limitations of sorting by price?

One issue I am facing is that the sorting functionality in the sortProductsByPrice (sortOrder) method doesn't work properly when products are deleted or added. Currently, sorting only applies to products that are already present in the this.products a ...

Ember.js Helper that mimics an Ajax request response

After extensive exploration and experimentation, it seems that returning a value from an ajax request in Emberjs is quite challenging. (I could be mistaken.) The issue appears to be related to the asynchronous nature of callbacks. Here lies my predicament ...

Transferring information from a webpage to a popup using executeScript: A guide

I've successfully retrieved data from a website, but I'm struggling to send it to popup.js. I attempted to use executeScript with a callback, but it's not working for me. popup.js function getData() { chrome.tabs.query({active: true, c ...