0

I am new to javascript and jquery. I need help to understand the following block of code:

An unordered list with 4 list items:

<ul>
  <li id="one" class="hot"><em>fresh</em> figs</li>
  <li id="two" class="hot">pine nuts</li>
  <li id="three" class="hot">honey</li>
  <li id="four">balsamic vinegar</li>
</ul>

The following is the jquery code -

$('li').width('50%');
$('li#two').width('75%');

I expect the width of the second list item to be 75% of 50% of the initial width (on page load). However, the width is only 75% of the initial width. I thought the first jquery statement affect the next one?

3
  • why not use css to set the width? Commented Oct 19, 2017 at 11:35
  • try following way $('li').css('width','50%'); $('li#two').css('width','75%') Commented Oct 19, 2017 at 11:35
  • Try using google before SO. Width in % refers to parent width. Commented Oct 19, 2017 at 12:18

2 Answers 2

2

This is the correct behaviour of jQuery.width() method. The code you should use is like this:

$("li#two").width($("li#two").width() * 0.75);

Because you need to get the 3 quarters of the current width. Not the initial width.

Sign up to request clarification or add additional context in comments.

Comments

1

When you specify percentage width, the percentage refers to the width of the parent (the ul in your case) and not the previous li width you have set. In other words, li#two is not a subset nor a child of li. What you can do is declare the initial width as a variable then use multiples of it, something like:

let originalWidth = 0.5;
function getPercentWidth(width) {
    return ((width * 100) + '%');
}
$('li').width(getPercentWidth(originalWidth));
$('li#two').width(getPercentWidth(0.75 * originalWidth));

3 Comments

Are you sure that percentage width refers to the parent width, and not the current width of the li (because width is not an inherited property) ?
When you provide a percentage width, you immediately ask the question: percentage of what ? And the answer is: the parent's width. Here is a codepen illustrating the behavior.
Thanks for the clarification. My confusion was due to the fact that I was changing the width set by CSS using jquery. But it is clear now.

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.