user3750929
user3750929

Reputation: 69

Any way to change the width of an element in real time?

So Im trying to change the width of a specific element in real time. Meaning that as you scale the browser window, the element changes width along with it.

Now, the way im calculating this width is by using another element as a reference point. So i just basically copy the reference element's width and apply it to my own element. However the problem is that this is only applied after every page refresh instead of a real time change.

Im using the following jquery code:

 $("#lists ul").css("width", $("#lists").width());

As you can see, the code is pretty simple. #lists ul is the elements whose width I am attempting to change and #lists is the reference element. My question is, is there a way to achieve this effect? or should I use a different approach? thanks for the help!

Upvotes: 0

Views: 1114

Answers (3)

Frank
Frank

Reputation: 2230

You can use a combination of JavaScript and CSS. I don't know what your specific needs are, but you can easily set the width of an object like this:

var element=document.getElementById("my_element");
element.style.width=10+"px";// Simple as that.

If you just want to scale your element based on its parent element's size, this is best done with CSS percent width and height.

CSS:

#my_element{
    width:20%;
}

Then CSS takes care of all your scaling needs whenever the parent element is resized.

CSS by itself may not look like what you want it to be, but if you make sure to define all applicable CSS properties of your element (like margin, padding, border, etc...) and then bolster the layout with JavaScript, you can do quite a bit.

Upvotes: 0

Dave Salomon
Dave Salomon

Reputation: 3287

What you're trying to do sounds crazy. As others have pointed out, using a percentage in CSS is probably much smarter.

If you insist on doing it this way though... I'm guessing your event is firing within $(document).ready(). Instead, try this.

$(window).resize(function(){
     $("#lists ul").css("width", $("#lists").width());
});

Upvotes: 1

woz
woz

Reputation: 11004

No need to use JavaScript to adjust widths. This should be all you need:

#lists ul { width: 100%; }

Upvotes: 4

Related Questions