1

Here is my javascript:

function scrollTo(position) {
    $('body').animate({
        scrollTop: position
    }, 500);
}

var titles = $('.title');
for(var i = 0; i < titles.length; i++) {
    titles[i].click(function() {
        console.log('click');
        scrollTo(0);
    });
}

It's supposed to select all three titles and apply a click listener that will scroll the page back to the top. Unfortunately I am not getting the message in the console nor is it scrolling.

Everywhere I have looked online has given for loops exactly like this to apply a click listener to multiple JQuery objects but for some reason it won't work for me. I'm afraid I may have made a stupid mistake but I can't find it.

2
  • You need $(titles[i]).click(...); for that to work. Or titles.eq(i).click(...) Commented Jun 21, 2017 at 0:52
  • titles[i] returns a DOM object Commented Jun 21, 2017 at 1:05

2 Answers 2

2

The reason your code did not work was because of this line

titles[i].click(function() {

When you access a jQuery object with a index, you are technically accessing the DOM element and not the jQuery object anymore. And the DOM object does not have a click method. If you would have opened your console, you would have seen an error. If you still want to use a for loop, you will have to convert that to a jQuery object first.

$(titles[i]).click(function() {

If you would have done that, it would work as expected.

Also if you still do not want to double wrap it, you could have also used .eq to get the jQuery object from the array.

titles.eq(i).click(function() {

You need not iterate over the jQuery objects to assign event handlers. You could just do it in one line.

$('.title').click(function() {
    console.log('click');
    scrollTo(0);
 });

Also check the version of jQuery you are using, if it is the latest then you could use on

$('.title').on('click', function() {

Also you need to make sure that the elements with class title are present on the page when you associate the events.

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

1 Comment

This worked thank you! Why would the way I did it not work? I've used .click() on single JQuery objects before.
1

you can use this, should give you what your looking for.

$('.title').click(function () {
   $('body,html').animate({
        scrollTop: 0
    }, 600);
    return false;
});

also as Sushanth said, if you have a new version of jQuery you can use .on(click)

Comments

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.