Mouse click failing to trigger CSS property update

I am attempting to create an accordion feature. I want the accordion to expand when hovering over the "accordion head," and also show/hide the accordion body when clicking on the "accordion head."

I have successfully implemented the show/hide functionality using CSS for hover events. However, I am facing issues with incorporating the mouse click event.

Here is a sample of what I have tried:

http://jsfiddle.net/yf4W8/157/

.accordion-body{display:none;}.accordion:hover div{display:block;}

Answer №1

You should make a modification to the following code snippet:

myElement.style.display = none;
myElement.style.display = block;  

The correct format should be:

myElement.style.display = "none";   //ensure double quotes are included
myElement.style.display = "block";  //ensure double quotes are included

Demo

Answer №2

Take a look at the demo I've put together below, which activates on mouse click. Use this JavaScript code to replace your current one and delete any unnecessary css properties.

function toggleAccordion() {
    var accordionBody = document.getElementById("accbody");
    var computedStyle = window.getComputedStyle(accordionBody, null);
    
    if(computedStyle.display === 'block') {
        accordionBody.style.display = 'none';
    } else {
        accordionBody.style.display = 'block';
    }
}

Check out the Demo

Answer №3

I decided to make a few tweaks to your code. The updated version now functions correctly, aligning with what you intended. Instead of relying solely on Javascript, I incorporated jQuery for the click and hover events.

For a demonstration, you can access the working code by clicking below:

Click here for DEMO

Below is the snippet of HTML code used:

<div class="accordion">
<div class="headA">
<a href="#">Head</a>
</div>
<div id="accbody" class="accordion-body">
<a href="#">Body</a>
</div>
</div>

The CSS styling applied is as follows:

.accordion {
  border: 1px solid #444;
  margin-left: 60px;
  width: 30%;
}

.accordion:hover div {
  display: block;
}

.accordion-body a {
  background-color: green;
  display: block;
  color: white;
  padding: 25px;
  text-align: center;
}

.headA a {
  text-align: center;
  display: block;
  background-color: yellow;
  padding: 25px;
}

And finally, the jQuery script utilized for the functionality:

$(document).ready(function() {
  // on page load hide accordion body
  var accordionBody = $('#accbody');
  accordionBody.hide();
  
  $('.headA').click(function() {
    if (accordionBody.is(':hidden')) {
      accordionBody.slideDown(400);
    } else {
      accordionBody.slideUp(400);
    }
  });

  $('.headA').hover(function() {
    if (accordionBody.is(':hidden')) {
      accordionBody.slideDown(400);
    } else {
      accordionBody.slideUp(400); 
    }
  });

});

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

The navigation bar in Bootstrap 3.2 expands in size as you scroll past it

Whenever I reach the bottom of the page, the navigation bar suddenly enlarges. The navbar is located at the top of my code. I attempted moving the navigation to the bottom of the code... but it didn't fix the issue... Could someone please identify wha ...

Disable the 'bouncy scrolling' feature for mobile devices

Is there a way to prevent the bouncy scrolling behavior on mobile devices? For example, when there is no content below to scroll, but you can still scroll up and then it bounces back when released. Here is my HTML structure: <html> <body> ...

Connecting Vue.JS page to my existing HTML page: A step-by-step guide

While developing my website, I faced a challenge with the structure. The home page was built using traditional HTML/CSS, while the other pages were created in Vue.js. Is there a method to connect these two different types of files? For instance, can I inc ...

Can a universal Save File As button be created for all web browsers?

Currently, I am in the process of developing a music player on the client side and I am seeking a method to save playlists that include mp3 data. Concerns with localStorage The restriction of a 5mb limit for localStorage makes it impractical for my needs. ...

How has the left-pad incident been avoided in the future?

Back in 2016, the maintainer of the left-pad package caused chaos by removing it from NPM, resulting in numerous broken builds. Fortunately, NPM intervened and re-published the package before things got too out of hand. Read more about it here What measu ...

Styling the large drop-down menu for Internet Explorer 7

Check out the code snippet at http://jsfiddle.net/jN5G4/1/ Is there a way to align the drop-down menu for "5 Columns" to match the alignment of the other drop-downs? After removing the <a href...> </a> tags from the 5 Columns list item, the d ...

The vertical scrolling issue arises when the content exceeds the height of the screen

Seeking a solution to enable scrolling of users within a flexbox menu, I've come across an interesting discovery. When setting a specific height in pixels for my nav element (like 100px), everything works perfectly. However, when I set the height to 1 ...

What is the best way to divide an array into pairs and store them in separate arrays?

I'm attempting to challenge my JavaScript skills and faced with a dilemma. There is an array containing data var array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];. The goal is to pair the elements and generate a new array of arrays such as var newArray = [[1 ...

The output of new Date() varies between app.js and ejs

app.get("/test",function(req,res){ var d = new Date(); res.send(d); }); When I access mydomain/test, it displays the output "2019-03-19T04:50:47.710Z" which is in UTC. app.get("/testejs",function(req,res){ res.render("testejs");}); Below is the content ...

I am looking to implement the ajax data variable for use in a submit button. How should

I'm facing an issue where, upon clicking the submit button, I am unable to receive the value yearend. Instead, I am getting an undefined value. How can I ensure that I receive the correct yearend value when I click the submit button? Here is my code: ...

What causes $(this) to stop functioning post successful execution?

Here are the code snippets I'm currently working with: $(this).removeClass('page larger').addClass('current'); $(this).siblings().removeClass('current').addClass('page larger'); Interestingly, when I try to pl ...

What is the best way to arrange an unordered list in a horizontal layout?

I have four lists that I want to display side by side. The first row should show a Doctor and Patient side by side, the second row should show a Pharma Company and Employee side by side. However, in my code, this layout is not working as intended. .tree ...

Creating a Scrolling Element in CSS Without Displaying a Scrollbar

Find the visuals and code on JSbin here. Looking to create a left sidebar that is full height with a fixed position, yet have its content accessible without scrollbars and no need for overflow: scroll. I'm hoping to achieve this in CSS only, without ...

Preventing the Current Page from Refreshing while in Use

Is there a way to prevent the current class from causing the page to reload using jQuery? For instance, on the About page, I want the current state to prevent users from reloading the page if they click on the link again. This way, any animations or progr ...

What is the process for implementing a security rule for sub-maps with unique identifiers in Firebase?

I am looking to implement a security rule ensuring that the quantity of a product cannot go below zero. Client-side request: FirebaseFirestore.instance .collection('$collectionPath') .doc('$uid') .update({'car ...

Is there a way to accomplish this without using settimeout?

Whenever the Like button is pressed, I want to trigger the loading process I expect to see LOAD_POST_SUCCESS immediately after LIKE_POST_SUCCESS Pressing the Like button should initiate the load process After LIKE_POST_SUCESS, I want to see LOAD_POST_SU ...

Grab and place to retrieve the ID of a table row

I am dealing with tables that have sub-tables. Here is a reference Fiddle. When I drag and drop rows from the sub-table, my code looks like this: $('.row_position>tr').each(function() { selectedData.push({'id':i,'key&ap ...

"Exploring the world of asynchronous computations in jQuery Ajax: The next steps post-GET

When using ajax in jQuery with the request type, URL, and success functions, I often receive a JSON response. However, I face the challenge of needing to reformat the JSON arrays into a different structure, which can be computationally expensive. I am seek ...

Sorting in MongoDB aggregation operations

I have a database containing user activities, and I want to calculate the number of active users and activities they performed each month. The results should be sorted by year first and then by month within each year. Here is my query: query = { ...

Combining NodeJS and ExpressJS to deliver a unified JavaScript file when in production mode

Currently, I am managing multiple individual JS files in the following way: <script defer src="/js/libs/jquery.min.js"></script> <script defer src="/js/libs/plugins.js"></script> <!-- application core --> <script defer sr ...