Jawad Asghar Ali
Jawad Asghar Ali

Reputation: 45

Getting CSS Properties and writing to the page live with jQuery

I am trying to get the names and values of CSS properties and write them to the page. The problem is the values don't change live i.e., e.g. the opacity should show a decreasing value from 1 to 0 live. Also the padding, border and margin values are not shown. This can be seen by opening up the page in firefox and using firebug to inspect it.

The Markup

<div id="container">
    <div id="box">click to hide me</div>
    <p id="result">&nbsp;</p>
</div>

The Styles

#container {
    overflow: auto;
}

#box {
    width: 400px;
    height: 400px;
    padding: 10px;
    border: 5px solid black;
    margin: 15px;
    background-color: red;
    text-align: center;
    float: left;
}

#result {
    width: 400px;
    height: 200px;
    border: 1px solid #CCCCCC;
    background-color: #EEE;
    float: right;
    margin-right: 20px;
}

The Script

$(document).ready(function() {
    $( "#box" ).click(function() {
        var html = [ "The clicked div has the following styles:" ];
        var styleProps = $( this ).css(["width", "height", "padding", "border", "margin", "opacity", "display"]);
        $.each( styleProps, function( prop, value ) {
            html.push( prop + ": " + value );
        });
        $( "#result" ).html( html.join( "<br>" ) );
    });

    $("#box").click(function() {
        $("#box").hide(5000);
    });
});

Just to be clear I am noob with jQuery/javascript and I am trying to find out which and what values the jQuery hide() method changes. Using firebug in firefox I see that the the height, width, border, padding, margin, opacity and display are nulled. I am trying to show that in the page itself in the result div.

fiddle

Upvotes: 0

Views: 147

Answers (1)

Eternal1
Eternal1

Reputation: 5625

You have several issues here.

  1. You cannot get margin, padding, and border css properties in one go. You need to get something like marginTop, paddingBottom, borderWidth and so on.
  2. You need to get status update to separate function, an then call it on progress of your hide.

    $.fn.update = function(element) {
        var html = [ "The clicked div has the following styles:" ];
        var styleProps = $( this ).css(["width", "height", "opacity", "display"]);
        $.each( styleProps, function( prop, value ) {
            html.push( prop + ": " + value );
        });
        element.html(html.join("<br>"));
    }
    
    var box = $("#box");
    
    box.click(function() {
        box.hide({
            duration: 5000, 
            progress: function() {
                box.update($("#result"));
            }
        });
    });
    

Fiddle for ya

Upvotes: 1

Related Questions