neoxxx
neoxxx

Reputation: 71

Changing margin of an element with Jquery

So, I have a div, named $slideshowContainer in jquery. I want to change it's left margin on resize to be a half of its width. I tried using

$slideshowContainer.css('margin-left',' + (' + $slideshowContainer.width() / 2) + 'px)';

and other similar variations, but it seems to not work (other resizes in the same function work well, so I guess there's something wrong in code above. I guess these pluses and apostrophes have something to do with it, I never really understood when to insert them in Javascript (I usually felt when I have to insert them, but when I didn't, I had no idea what's wrong)

Also if someone had a guide explaining where to insert pluses and apostrophes in situations like this, it would be really helpful (I tried to search for one but never found it)

PS: The code above of course was in the resize function, it didn't work. Just saying in case it wasn't clear

Thanks in advance for help

Upvotes: 0

Views: 48

Answers (2)

MARSHMALLOW
MARSHMALLOW

Reputation: 1395

Try this:

$slideshowContainer.css('margin-left', + ($slideshowContainer.width() / 2) + 'px;');

Upvotes: 1

Terry
Terry

Reputation: 66228

Remove the wrapping (...) around your pixel value. There is also syntax error with your code. All you need is this:

$slideshowContainer.css('margin-left', ($slideshowContainer.width() / 2) + 'px');

If you are keen on using ES6 template literal syntax, it makes things a lot more readable:

$slideshowContainer.css('margin-left', `${$slideshowContainer.width() / 2}px`;

Upvotes: 2

Related Questions