Tobias Glaus
Tobias Glaus

Reputation: 3628

Reference Error: variable is not defined

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";

Upvotes: 4

Views: 1838

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337656

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');
        }
    });
});

Upvotes: 3

Related Questions