0

I have to set an element from display: none to display: inline-block
when clicking on another element.

Jquery always detects it display: none

(function ($) {
    $(document).ready(function() {
        $("#click").click(function () {
            if($("#show").css('display','none')) {
                $('#show').css('display','inline-block');
            } else {
                $('#show').css('display','none');
            }
        });
    });
})(jQuery);
#show {
    display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="click">
    Click
</div>
<div id="show">
    Text
</div>

Fiddle

0

3 Answers 3

4

The if statement is wrong,

if($("#show").css('display','none'))

You are assigning the css property to the show element in your if statement, use .is(':visible') instead.

if(!$("#show").is(':visible'))
Sign up to request clarification or add additional context in comments.

2 Comments

This answer explains what's wrong instead of just giving the "fixed" code. +1
Well I rather know what's wrong and what has to be replaced
1

Update your if() to use the is(':visible') function:

var displayType = ( ! $("#show").is(':visible') ) ? 'inline-block' 
                                                  : 'none';

$('#show').css('display', displayType);

jsFiddle Demo

4 Comments

Your fiddle is running onload - that can't be right
You have a fiddle set to run onload, that will wrap it in $(function() {} , then your code is wrapped in $(function($) {} and inside that you have $(document).ready...
@mplungjan I just updated the OP's Fiddle. Didn't change the options. Oh, and onload !== $(function() { }). That's a wrapper for DOMReady.
Still a waste of event handlers
1

Like many jQuery functions, css has two different behavior, based on the parameters you pass.

If you pass just the first parameter (the css property), it returns the value of the css property.

If you pass the css property and the value, it set the value and returns the actual jQuery object.

Try this:

(function ($) {
    $(document).ready(function() {
    $("#click").click(function () {
        //Get the div in jquery object.
        var div = $("#show");
        //Determine the actual value of the display.
        var display = div.css('display');

        //Determine the desired value.
        if (display == 'none')
            display = 'inline-block';
        else
            display = 'none';

        //Change the value
        div.css('display', display);

        });
    });
})(jQuery);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.