Strategies for identifying CSS properties within a div element

I am attempting to identify the CSS property display of a div. If it is set to display:block, I want to change the icon to -. If it is set to display:none, I want to change the icon to +.

I have tried using the following code but it does not seem to work:

if($('#ceo').css('display') == 'none'){ 
    $("#button img").css({top:"-18px"});
} else {
    $("#button img").css({top:"9px"});
}

My goal is to create a collapsible tree structure. Here is my Fiddle

Answer №1

I have implemented significant changes and revised some of the code. It appears to be working well now: Check out the demo on jsfiddle

function adjustPosition(element, direction) {
    var value;
    if (direction == 1) {
        value = "9px";
    } else {
        value = "-18px";
    }
    $("img", element).stop().animate({
        top: value
    }, {
        queue: false,
        duration: 200
    });
}

$(document).ready(function () {
    $("#button").click(function () {
        // Check if #ceo display:block, set image position accordingly
        if ($('#ceo').css('display') == 'none') {
            adjustPosition($("#button"), 1);
        } else {
            adjustPosition($("#button"), 2);
        }
        $("#ceo").fadeToggle("fast", "linear");
        $("#button2").fadeToggle("fast", "linear");
    });

    $("#button2").click(function () {
        if ($('#division').css('display') == 'none') {
            adjustPosition($("#button2"), 1);
        } else {
            adjustPosition($("#button2"), 2);
        }
        $("#division").fadeToggle("fast", "linear");
    });
});

Answer №2

In my personal experience, I find myself struggling with JavaScript. While the code I currently have in http://jsfiddle.net/jennift/DESkX/1/ is functional, I believe there is room for improvement:

$(document).ready(function(){
    $("#button").click(function(){

        // Check if #ceo display:block, set image to minus
        if($('#ceo').css('display') == 'none'){ 
            $("img", this).stop().animate({top:"9px"},{queue:false,duration:200});
        } else {
            $("img", this).stop().animate({top:"-18px"},{queue:false,duration:200});
        }

        $("#ceo").fadeToggle("fast", "linear");
        $("#button2").fadeToggle("fast", "linear");
    });

    $("#button2").click(function(){  
        if ($("#division").css('display') == 'none') {
            $("img", this).stop().animate({top:"9px"},{queue:false,duration:200});
        } else {
            $("img", this).stop().animate({top:"-18px"},{queue:false,duration:200});                    
        }

        $("#division").fadeToggle("fast", "linear");
    });

});

Answer №3

To obtain the true display value, you can utilize computed style.

window.getComputedStyle( document.getElementById("#ceo"), null).getPropertyValue("display")

Using $('#ceo').css('display') will only reveal the inline style display value.

Answer №4

Here is a snippet of JavaScript code that you can experiment with:

function swapImage()
{
element=document.getElementById('myimage')
if (element.src.match("maximze_icon"))
  {
  element.src="images/minimize_icon.gif";
  }
else
  {
  element.src="images/maximze_icon.gif"; 
  }
}
var state = 'block';

function toggleDisplay(layer_ref) {

if (state == 'block') {
state = 'none';
}
else {
state = 'block';
}
if (document.all) { // For IE versions less than 7
eval( "document.all." + layer_ref + ".style.display = state");
}
if (document.layers) { // For Netscape Navigator 4 or lower
document.layers[layer_ref].display = state;
}
if (document.getElementById &&!document.all) {
hza = document.getElementById(layer_ref);
hza.style.display = state;
}
}

Feel free to use the HTML code below in your project:

<img id="myimage" onclick="toggleDisplay('div1'); swapImage()" src="images/minimize_icon.gif"><a href="#" onclick="toggleDisplay('div1'); swapImage()">Click Me</a>

Answer №5

Here is a potential solution for you:

$(function(){
    $("#button2").hover(function(){
        $("img", this).stop().animate({top:"9px"},{queue:false,duration:200});
    }, function() {
        $("img", this).stop().animate({top:"-18px"},{queue:false,duration:200});
    });
});

$(document).ready(function(){
    $("#button").click(function(){

        // Check if #ceo display:block, set image to minus
        if($('#ceo').css('display') == 'none'){ 
            $("#button img").css({top:"9px"});
        } else {
            $("#button img").css({top:"-18px"});
        }

        $("#ceo").fadeToggle("fast", "linear");
        $("#button2").fadeToggle("fast", "linear");
    });

    $("#button2").click(function(){
        $("#division").fadeToggle("fast", "linear");
    });
});

Try out the demo here>>

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 steps can I take to embed a video in HTML without autoplaying in a browser?

I have a simple but important question that I need help with. I am creating a compilation of family videos and I want to put them all on one page or in an HTML file. However, when I embed/link a directory file of the video into the HTML, it automatically ...

CSS files are failing to load in ASP .NET framework

I am facing a similar issue to the one described by another user on Stack Overflow here: Asp.NET not applying my CSS files However, after adding the following code to my web.config file, nothing seems to change: <location path="css"> &l ...

Tips for connecting an event to an object for resizing and clicking

I have been working with jQuery version 1.4.1 and attempting to assign resize and click events in this manner, but it does not seem to be functioning as expected. var $elements = []; $elements.window = $(window); $elements.window.bind('resize', ...

Turning a jQuery object and its contents into a string

Currently, I am selecting multiple jQuery objects to store in an array and then display them as HTML later on. I am attempting to transform the jQuery object into a text string so it can be displayed as HTML in the future. My current approach is as follo ...

Formatting your HTML tags in Visual Studio

For instance, I have this particular tag with concise content <div>It is brief</div> However, upon formatting, Visual Web Developer presents it as <div> It is brief</div> which is unattractive. What I desire is <div> ...

What causes an iframe to scroll horizontally when scaled?

I'm in the process of resizing an iframe element on my webpage using a CSS media query to adjust its dimensions. However, when I scale it down and interact with the iframe, my webpage starts scrolling horizontally. The issue is evident when using Chro ...

Enhance the appearance of the standard black rectangle displaying the messages "No video source" or "No video permissions"

Is there a way to change the styling of the video element that appears as a black rectangle with a strikethrough play button when the user is prompted for permission on Safari? Does it have a specific ID, class, or tag that can be targeted? I'm curre ...

How can you attach a d3 graphic to a table that was created automatically?

Calling all experts in d3, I require urgent assistance!! On this web page, a JSON is fetched from the server containing 50 different arrays of numbers and related data such as 90th percentiles, averages, etc. A table is dynamically created with the basic ...

Issue with Div element not appearing on Azure AD B2C page customization

Utilizing PopperJS, I attempted to incorporate a popover box that appears when the user focuses on the password field within an Azure AD B2C page customization. Despite noticing the presence of the box element, it fails to display as intended. Any assistan ...

Swap out the CSS line for a PHP conditional statement

My goal is to change a CSS line when a specific condition is met. When I click on the Ok button, a lot of data is displayed. Depending on the selection made in a combo-box, I want the text to appear either in red or black. I tried using JavaScript for this ...

Meta tags are causing issues with HTML5 validation on the website

Striving to enhance the HTML validity of my website, I encountered several errors in the meta tags that are marked as invalid. Unfortunately, I am unsure how to modify them to rectify these errors. <meta http-equiv="X-UA-Compatible" content="IE=edge,ch ...

Single quotation mishap in JSON

How can I successfully send JSON data that contains single quotes without encountering errors? I need to include values with single quotes, but how can I do this without causing any issues? $.ajax({ type: "post", url: "canliAyarlari.aspx/dosyaYa ...

Transforming the Date Format using jQuery UI Datepicker and Ruby on Rails: A Step-by-Step Guide

Dealing with the date picker has proven to be quite a challenge. Despite browsing through numerous questions on StackOverflow, I haven't been able to figure out how to get the formatting right. Following the Railscasts #213 Calendars (revised) tutoria ...

Animating the background of an element to be null using jQuery

When hovering over an element with no background, I've implemented a hover effect that animates the background color. The animation works on hover, but does not revert back to no background when not hovered: $('#home_sensors_products').hove ...

JavaScript: Code for creating an overlay component

As someone who is new to javascript and Jquery, I have very little understanding of what I am doing. I have been relying on trial and error to make progress so far. While I am aware that users have the ability to disable javascript, I prefer not to use PHP ...

Delegate All Events to the Document

In my current setup, I have over 350 events that look like: $(document).on('click','.removable-init',function(){}); I've noticed a performance issue where some click events are delayed by a fraction of a second. This is happening ...

Perform a postback within a jQuery UI dialog box

Despite many solutions being available from various Stack Overflow users, none seem to be effective for me. In aspx <asp:Button ID="btnConfirm" ClientIDMode="Static" runat="server" Text="Confirm" OnClick="btnConfirm_Click"/> <script type="text/ ...

How can JavaScript be used to remove HTML tags from text while preserving a space between each line?

I found a helpful solution on Stack Overflow for removing HTML from text content. This is the method it suggests: function strip(html){ let doc = new DOMParser().parseFromString(html, 'text/html'); return doc.body.textContent || "&quo ...

Retrieve the most recent 5 entries from a database using PHP and display them in an ordered list on an HTML page

Currently, I am in the process of learning how to populate an ordered list within an HTML page with the 5 most recent records from a table using PHP. While I have managed to grasp most components (with some difficulties in PHP), my main challenge lies in e ...

Layers of CSS images

Is there a way to create multiple layers for images on a webpage so they can move independently without affecting other elements? I attempted to use z-index, which did work, but it caused the page to increase in height. Additionally, when using jQuery.posi ...