Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use a jQuery variable in CSS property

I having the following jQuery which finds the height of a responsive image:

        $(document).ready( function() { //Fires when DOM is loaded
            getImageSizes();
            $(window).resize(function() { //Fires when window is resized
                getImageSizes();
            });
        });
        function getImageSizes() {
            $("#slideshow img").each(function() {
                var $height = $(this);
                console.log( $height.height() );

            });

        }

And my goal is to use the $height variable to specify the height of a div with the ID of slideshow.

I assume I can use this:

$('#slideshow').css({'height': $height + 'px;'});

However it is not working (no height is specified).

I included the above line like so:

        $(document).ready( function() { //Fires when DOM is loaded
            getImageSizes();
            $(window).resize(function() { //Fires when window is resized
                getImageSizes();
            });
        });
        function getImageSizes() {
            $("#slideshow img").each(function() {
                var $height = $(this);
                console.log( $height.height() );

                $('#slideshow').css({'height': $height + 'px;'});
            });

        }

Is there something I am missing?

like image 201
Raphael Rafatpanah Avatar asked Mar 04 '13 19:03

Raphael Rafatpanah


People also ask

Can you use jQuery in CSS?

jQuery is called with and represented by the dollar sign ( $ ). You access the DOM with jQuery using mostly CSS syntax, and apply an action with a method.

Can you use a JS variable in CSS?

CSS variables have access to the DOM, which means that you can change them with JavaScript.

Can we change CSS property value using jQuery?

It is possible to change the CSS property of an element by using a simple JavaScript API, but we try to complete this challenge using jQuery css() method. Syntax: $(). css(propertyname, value); $().

Can you pass a variable into CSS?

Like most programming languages, native CSS now has support for variables, and they're here to stay. If you know a bit of CSS, chances are you've heard of CSS preprocessors such as Sass and Less. You've probably used them in your projects regardless of your frontend framework of choice.


1 Answers

You are logging $height.height(), but then only using $height in the CSS.

If you named your variables better, it would be easier :p

var $height = $(this).height();
$("#slideshow").css({"height":$height+"px"});

Or my preference:

document.getElementById('slideshow').style.height = this.height+"px";
like image 143
Niet the Dark Absol Avatar answered Oct 04 '22 07:10

Niet the Dark Absol