4

I got a variable called "nthchild" var nthchild = ($(ui.selected).index() + 1); This gives me the nth-child of a list item with the class selected. I even log it in the console and it works fine. However when I try to use this variable but it doesn't work.

$("section:nth-child(" + nthchild + ")").style.marginTop = "200px";

So it should give the section a margin-top of 200px. But the console is giving me the error

Uncaught ReferenceError: nthchild is not defined

You can find my code on this codepen

$(function() {
    $("#selectable").selectable();
});

$(function() {
    $("#selectable").selectable({
        selected: function(event, ui) {
            var nthchild = ($(ui.selected).index() + 1);
            console.log(nthchild);
        }
    });
});

$("section:nth-child(" + nthchild + ")").style.marginTop = "200px";
0

1 Answer 1

3

The issue is because you define nthchild out of scope of the location you attempt to use it. To fix this place the :nth-child selector within the selected callback so that it's executed when the selectable is updated.

Also note that .style.marginTop is a property of a native Element which is not available on a jQuery object. Instead, use the css() method, or better yet, put the style in a rule in an external stylesheet and use addClass(). Try this:

$(function() {
    $("#selectable").selectable();

    $("#selectable").selectable({
        selected: function(event, ui) {
            var nthchild = ($(ui.selected).index() + 1);
            $("section:nth-child(" + nthchild + ")").css('marginTop', '200px');
        }
    });
});
Sign up to request clarification or add additional context in comments.

3 Comments

Shouldn't be $("section:nth-child(" + nthchild + ")").css({'margin-top':'200px'}); or document.getElementsByTagName("section")[nthchild ].style.marginTop = "200px";
Right. That works perfectly! But now the divs dont go back to their original position when I unselect them :/
@TobiasGlaus you can use jquery :not() selector add $("section:not(:nth-child(" + nthchild + "))").css('marginTop', '');

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.