JavaScript's connection to the CSS property visibility seems to be causing some issues

The Javascript code seems to be ignoring the CSS display property, even though it's set in the style sheet. I added a debugger statement and noticed that the display value was empty. I've been staring at this for some time now, so I must be overlooking something obvious.

<html>
<head>
<style type="text/css">
    div#image{ display: none; }
    div#url { display: none; }
</style>
<script type="text/javascript">
    function toggleVisibility(id) {
    debugger;
        var imageStyle = document.getElementById('image').style;
        var urlStyle = document.getElementById('url').style;
        alert(document.getElementById("image").style.display); // debug for stack
        if ( id == "image" ) {
            if ( imageStyle.display == "none" ) {
                imageStyle.display = "block";
                urlStyle.display = "none";
            }
        }

        if ( id == "url" ) {
            if ( urlStyle.display == "none" ) {
                urlStyle.display = "block";
                imageStyle.display = "none";
            }
        }
    }
</script>
</head>
<body>
    <form method="post" action="create.php">
        <input type="hidden" name="formType" value="create">
        <input type="radio" name="type" value="image" onClick="toggleVisibility('image');"> Image <input type="radio" name="type" value="url" onClick="toggleVisibility('url');"> URL
        <div id="image">
            Image div
        </div>
        <div id="url">
            URL div
        </div>
    </form>
</body>
</html>

Answer №1

Check out the Demo

It's not possible to directly read CSS styles of attributes in that manner, but a workaround is to check for an empty value and treat it as if it were set to display:none

if (id == "image") {
    if (imageStyle.display == "none" || !imageStyle.display) {
        imageStyle.display = "block";
        urlStyle.display = "none";
    }
}

if (id == "url") {
    if (urlStyle.display == "none" || !urlStyle.display) {
        urlStyle.display = "block";
        imageStyle.display = "none";
    }
}

Answer №2

To retrieve the computed style of the element, you need to use the following function:

function getStyle( target, property ) {
    var computedValue;

    if (target.currentStyle) {
        computedValue = target.currentStyle[property];
    } else if (window.getComputedStyle) {
        computedValue = document.defaultView.getComputedStyle(target, null).getPropertyValue(property);
    }
    return computedValue;       
}

I've also made some simplifications in your JavaScript code, eliminating the need to directly check the style of the element:

if ( id === "image" ) {
    imageStyle.display = "block";
    urlStyle.display = "none";
}

if ( id === "url" ) {
    urlStyle.display = "block";
    imageStyle.display = "none";
}

Check out the demo here

Answer №3

Reading styles from elements in JavaScript directly from a style sheet can be a bit tricky. To achieve this, you may need to utilize jQuery or other libraries. One way to make it work is by setting the style attribute on the HTML tag itself:

<div id="image" style="display:none">
    Image div
</div>
<div id="url" style="display:none">
    URL div
</div>

Alternatively, you can check for an empty value and use that as "none".

Answer №4

The style attribute on HTMLElement objects only displays the inline styles applied to that element (such as the style attribute in the tag). To access the computed style of an element, including styles applied by CSS rules, you need to utilize getComputedStyle (for supported browsers) or currentStyle (for supported browsers).


On a different note: Obtaining the computed style for an element reliably is one of the many areas where a reliable JavaScript library can save you time and effort, whether it's jQuery, Prototype, YUI, Closure, or any of several others. It's not just about the getComputedStyle / currentStyle difference, but also about various browser inconsistencies. By using a trusted library, you can benefit from the extensive research and work done by others, allowing you to focus on your specific tasks. Usually. :-)

For example, with jQuery, you can determine if the element with the id "image" is visible (which can be influenced by display: none, visibility: hidden, etc.) using the following code:

if ($("#image").visible()) {
    // The element is visible
}

Or if you wish to check a specific computed style:

if ($("#image").css("display") === "none") {
    // It is styled with display: none, either directly or by a rule
}

Similar functionality will be available in other libraries as well.

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

Having trouble retrieving data using a custom URL in Axios with ReactJs

My knowledge of Reactjs is still new and I am currently working on a project using nextjs. I have a component called Trending.js that successfully fetches data from the URL "https://jsonplaceholder.typicode.com/users". However, when I try to change the U ...

Best practices for structuring npm scripts and multiple webpack configurations

My project consists of multiple dashboards, and I've decided to create separate scripts in my package.json for each one. Building all the dashboards during development when you only need to work on one can be time-consuming. So, I discovered that it&a ...

Filtering out Objection/Knex query results based on withGraphFetched results

I am working with two models in Objection - "brands" and "offers". Brand: const { Model } = require('objection') class Brand extends Model { static get tableName() { return 'brands' } ...

Is there a way to configure a Mui textfield to only allow numeric input? It currently accepts numbers, the letter "e," and dashes

Take a look at my current code. <TextField error={values[1].error} fullWidth id="id" type="number" value={values[1].Id} placeholder='Enter ID' onChange={handleChange(1,'Id')} variant="outlined" inputProps={{min: 0,inputMode: &apos ...

How to Implement Double Click Functionality in VueJS

I am facing an issue with my table where the columns have varying widths. To implement sticky headers, I need to calculate the column widths accurately. Initially, I created a function that increases the column width when double-clicking on the header. Su ...

Does anyone have tips on how to upload images to MongoDB using React?

Currently, I am working on a project that requires an image upload feature for users. These images need to be stored in MongoDB so that they can be viewed by the user later on. Can anyone offer assistance with this? I have successfully configured my datab ...

Problem occurring with Bulma CDN version 0.8.0 failing to identify the spacing helper

Recently revisited an older project I had started some time ago using the Bulma framework. However, for some reason, the 0.8.0 CDN is not being imported or recognized correctly by the spacing classes. Here's the code snippet I had initially: <link ...

Invoke index functions within a component

I have a widget/component written in Angular 4 within the index.html file. Before and after this angular app, there are various HTML elements due to the nature of it being an additional component for the website. The head section of the index file include ...

Retrieving information from a child component in Vue.js

I've been grappling with retrieving data from a child component using Vue.js. In my parent component, I need to display this data which is selectable in a Bootstrap table within the child component. Here's what I've done so far: Parent compo ...

Issue with Ajax form submission - unable to retrieve POST data in PHP

My goal is to utilize Ajax for form submission. Upon clicking the button, the hit() function will be triggered and send the data from the textbox back to test.php The issue arises with $_POST being empty as indicated by the alert message from Ajax (form w ...

Positioning a material UI dialog in the middle of the screen, taking into account variations in its height

Dealing with an MUI Dialog that has a dynamic height can be frustrating, especially when it starts to "jump around" the screen as it adjusts to fit the content filtered by the user. Take a look at this issue: https://i.stack.imgur.com/IndlU.gif An easy f ...

When navigating between Dynamic Pages using NuxtLink, the store data is not accessible

Check out the demo below. Click here for stackblitz When transitioning from a top page to a post page, the correct content is displayed. However, moving from one post page to another does not display the correct content immediately. Reloading the page w ...

Ways to showcase the chosen image from the input field?

Can someone help me with an issue I'm having regarding displaying selected images? Every time I try, I encounter this error message: Not allowed to load local resource: Any suggestions or insights into why this might be happening? <input type=&a ...

When utilizing the .populate() method in Mongoose, how can you retrieve and append ObjectIds with extra attributes to an array (which is returned by .populate()) collected from the

When using the .populate() method in Mongoose, how can I retrieve and add ObjectIds with additional properties to an array (returned by .populate()) if their corresponding document in the collection no longer exists? This question pertains to MongoDB and ...

Executing MySQL queries using Ajax

Having trouble with a registration form that relies on jQuery and Ajax for validation. The issue arises when the server-side validation of the e-mail address, among other things, fails to return a result through $msg. function checkUser () { $search = ...

Ways to conceal CSS on the page when triggering a different element

I am trying to achieve the functionality of hiding the black arrow when clicking on the green arrow, all without using jQuery. Here is my fiddle: http://jsfiddle.net/t5Nf8/195/ html: <div class="arrow-down"></div> <div class="arrow-up"> ...

Acquiring the index of a selector event within a list of dynamic elements

I am seeking guidance on how to go about solving the issue of obtaining an event index. I have a hunch that closures might play a role in the solution and would appreciate some insights. Initially, I dynamically build an HTML5 video container using an aja ...

I am consistently running into an Uncaught Syntax error within my Express server.js while using Angular 1.5.6

I've been struggling for hours to integrate Angular with routes that I've created. Eventually, I decided to give Express a try and set up a basic server.js file to run as a standalone server. However, nothing seems to be working and I keep encou ...

The login page allows entry of any password

I'm running a xamp-based webserver with an attendance system installed. I have 10 registered users who are supposed to log in individually to enter their attendance. However, there seems to be an issue on the login page where any password is accepted ...

Obtaining an element in the Document Object Model (DOM) following

There are numerous questions and answers regarding this issue, but I am struggling to adapt it to my specific case. My extension fetches positions (1,2,...100) on the scores pages of a game. Upon initial page load, I receive the first 100 positions. Howev ...