0

I'm having a bit of trouble with adjusting the code according to window width. If the window width is less than 450, I want it to scroll to a certain part, else another. Where am I going wrong?

$('.artist-kina').click(function( e ){
    e.preventDefault();
    $('html, body').animate({
        if ($(window).width() < 450 {
            scrollTop: $('#artists').offset().top - 60
        }
        else {
            scrollTop: $('#artists').offset().top - 115
        }
    }, 500);
    $('.artists-home').fadeOut(function() {
        $('.kina-gallery').fadeIn('slow');
    });
});
6
  • You have forgotten a parentheses in your if structure: if ($(window).width()) Commented Sep 13, 2014 at 13:27
  • @Pieter I put that in and now I'm getting an error on that line for an unexpected (. Here's the error: Error on line 148 col 6 Unexpected token punc «(», expected punc «:» Commented Sep 13, 2014 at 13:30
  • ^ put the parantesis after 450 so if ($(window).width() < 450) { Commented Sep 13, 2014 at 13:33
  • @Arijoon I did that but I'm still getting the same error. Commented Sep 13, 2014 at 13:34
  • My mistake, typed to fast! Commented Sep 13, 2014 at 13:34

2 Answers 2

3

The parenthesis was a problem, but in a larger sense the syntax is just completely wrong:

$('html, body').animate({
    scrollTop: $("#artists").offset().top - (
      $(window).width() < 450 ? 60 : 115
    )
}, 500);

You can't just drop an if statement into the middle of an object literal. You can, however, use the ? : operator to make a choice between values as part of an expression.

Now be aware that fooling around with the scroll position of the <body> may or may not work in all browsers. Safari used to have a problem with that; it may work in more modern versions of the browser.

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

2 Comments

I was thinking about the same thing but the way you wrote it is very neat. +1
Thank you very much. This helps and I'll remember this from now on.
0

There were several issues with the way that you nested the code, but the largest issue was the Animate call.

This should work:

$('.artist-kina').click(function( e ){
    e.preventDefault();
    if ($(window).width() < 450) {
        $("html, body").animate({
            scrollTop: $('#artists').offset().top-60
        }, 500);
    }
    else {
        $("html, body").animate({
            scrollTop: $('#artists').offset().top-115
        }, 500);
    }
    $('.artists-home').fadeOut('slow', function() {
        $('.kina-gallery').fadeIn('slow');
    });
});

Here is a working jsFiddle: http://jsfiddle.net/yy1v940u/5/

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.