What causes inline CSS and internal CSS to exhibit different behaviors?

It’s kind of strange that I have to click twice to see Foo’s content, but only once to see Bar’s content. The main difference seems to be that Foo’s content has internal style while Bar has inline style.

<html>

<head>
  <style>
    .content {
      display: none;
    }
  </style>

  <script>
    function showHide(element) {
      sibling = element.nextElementSibling;
      if (sibling.style.display == "none")
        sibling.style.display = "block"
      else sibling.style.display = "none";
    }
  </script>
</head>

<body>
  <h1 onclick="showHide(this)">Foo</h1>
  <div class="content">
    Foo Content
  </div>

  <h1 onclick="showHide(this)">Bar</h1>
  <div style="display: none;">
    Bar Content
  </div>
</body>

</html>

You can find the code on jsfiddle here

I’m really interested in achieving the same behavior with internal CSS or external CSS that I currently have with inline CSS. Do you think this is possible? I know it might be a simple issue, but I’m not quite sure which concepts to explore further.

Answer №1

When accessing sibling.style.display in JavaScript, you will retrieve the inline display style of that particular element. If there is no inline display style defined, the result will be "". You can also obtain the computed style by visiting this link, but a more effective approach is to avoid directly setting styles in JavaScript and instead manipulate classes:

function showHide(element) {
    const sibling = element.nextElementSibling;
    sibling.classList.toggle("content-hidden");
}
.content-hidden {
    display: none;
}
<h1 onclick="showHide(this)">Foo</h1>
<div class="content-hidden">
    Foo Content
</div>

<h1 onclick="showHide(this)">Bar</h1>
<div class="content-hidden">
    Bar Content
</div>

If you are specifically targeting a scenario like this, you may want to consider using <details>:

.thing > summary {
  display: flex;
}
<details class="thing">
    <summary><h1>Foo</h1></summary>
    Foo Content
</details>

<details class="thing">
    <summary><h1>Bar</h1></summary>
    Bar Content
</details>

Answer №2

The problem arises from the fact that when you use sibling.style.display, it is referencing the style attribute rather than the computed style of the element. This is why clicking it again will work, as the first click sets the style to display: none, and a subsequent click will make it visible.

To overcome this, you can utilize the element's classList to toggle a class that controls visibility, like in this example.

function toggleVisibility(element) {
  sibling = element.nextElementSibling;
  sibling.classList.toggle('visible')
}
.content {
  display: none;
}

.visible {
  display: block;
}
<h1 onclick="toggleVisibility(this)">Foo</h1>
<div class="content">
  Foo Content
</div>

<h1 onclick="toggleVisibility(this)">Bar</h1>
<div class="content">
  Bar Content
</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

Searching for Bluetooth devices using React Native

In my project, I am working on scanning HM-10 BLE with a react-native app. To achieve this, I referred to the example provided in Scanning for Bluetooth devices with React Native. So far, the library seems to be successfully installed without any errors du ...

What is the best way to modify CSS animation property without causing any disruptions?

Could you help me with modifying this CSS animation? I want to adjust the animation-iteration-count to 1 only when a certain property, status, is added to the element. Currently, the animation is not working as expected. For example: setTimeout(() => ...

Tips for personalizing the FileField in wtforms to function as an image button

I'm attempting to display an image from my project's directory as an icon instead of the standard "choose file" button. Unfortunately, my attempts thus far have been unsuccessful. Not only is the image not loading, but the original button is only ...

Checking for similarities between two string arrays to determine if there are any matching values using JavaScript and jQuery

Hey there, I'm currently working on a project where I need to compare two arrays and hide a list element if any values match. The first array consists of tags attached to list items, while the second array is user input. I'm facing some difficu ...

Creating a clickable image in the header of an R Shiny app

I've been attempting to create a hyperlink from the image output, but I'm encountering difficulties despite reviewing similar questions on Stack Overflow. svg with clickable links in shiny - not clickable The tags are not working. server.r li ...

Updating the state of a React component through a button click using React-JS

In my React-JS project, I am using Semantic-ui to create form inputs and a submit button. These forms have a property called 'error', and the value of this property is determined by the state. The issue arises when I click on the 'Next&apos ...

Looking to conduct date comparisons within angular-ui-grid?

I'm currently working on an application that utilizes angular-ui-grid to display form data. One issue I'm facing is how to compare the submission date obtained from an API call with the current date within ui-grid, in order to calculate the numbe ...

Updates made to CSS are not reflecting on the error 404 page

Unable to Apply CSS Changes to 404 Error Page EDIT: page in question: Right from the start: I have ruled out any relative path issues. I have specified a base href in my header like this: <base href="https://hinnahackers.no/"> I am aware that thi ...

Issue with Ionic toggles not updating the correct local storage entry

Encountering an issue with ionic toggles where changing any toggle affects only the last if statement below in local storage. Here is the list of toggles... $scope.settingsList = [ { text: "GBP", checked: gbpON }, { text: "USD", checked: usdON } ...

The powerful combination of Ajax and Django creates a dynamic Like button

Encountering difficulties while trying to implement a basic like button feature. Despite following various tutorials, clicking on the Like button does not yield any action. See below: models.py class Comentario (models.Model): titulo = models.CharFie ...

Progressing through the Material UI LinearProgress bar in steps

How can I split a progress bar into more steps to achieve a design like this? https://i.stack.imgur.com/lRMj6.png I attempted using this code but couldn't find an option for splitting: <LinearProgress variant="determinate" classes={{ ...

Conceal HTML components on certain devices

I am interested in customizing the display of HTML elements on different devices to enhance the overall design for specific viewing experiences. For example, I want to optimize the layout when accessing the page on an iPad as opposed to a PC. In order to ...

Ways to make an image wander aimlessly across a webpage while also spinning as it moves (with the help of jQuery or CSS)

I am working on making a div randomly move around a page. This is a related question Now, I have replaced the div with a picture like an "arrow" and I want it to randomly move while also pointing in the right direction by changing its rotation angle as i ...

Alert: CSS 4.0 Warning Validation - The value "rgb(0, 0, 0, 0.4)" is not valid for the "border" property

Wrapping up my asp core 3 project, I've been addressing various warnings that have popped up. However, one particular warning has me stumped. The CSS property in question is functioning perfectly, adding a touch of transparency to the black border. Wh ...

What steps can be taken to ensure that the scale() function is given the highest priority

Trying to develop a program that generates a canvas graph based on some calculated data. To adjust for larger numbers, I attempted to scale the graph using ctx.scale();. However, every time I do this, the canvas goes blank! I even tried scaling the canvas ...

The image appears uniquely sized and positioned on every screen it is viewed on

After reviewing the previously answered topics on the site, I couldn't seem to make the necessary adjustments. Despite setting the size and location in the css file, the large image remains centered and fitting for the screen. The "imaged1" class seem ...

Having trouble getting a background image to show up using node.js?

Hi there, I have a quick and simple question. I am attempting to include a div with a background-image in my *.ejs page file. <style> .signPage{ background-image: url("//back.jpg"); width: 98%; height: 98vh; top: ...

Retrieving a Table Row from a TableView in Titanium Mobile

Does anyone know where the actual tableViewRows are stored within a TableView? When inspecting the TableView, I can see the headings for the Rows but not the Rows themselves. Can someone point me in the right direction to find where these Rows are contai ...

PHP and MySQLi for inserting records into database

Currently, I am attempting to retrieve user input values from a form and store them in a database using PHP. Below is the contents of my dbConfig file: <?php $mysqli = new mysqli("localhost", "root", "password", "testDB"); /* checking connecti ...

The v-list-group does not automatically expand sub-groups based on the path specified in the group prop

I have a navigation sidebar that includes nested v-list-groups. Based on the documentation, the "group" prop of v-list-group should expand based on the route namespace. To see more information, visit: https://vuetifyjs.com/en/components/lists/ While this ...