Frage

I have the following script:

$(".a").click ->
    $("body").animatescroll({scrollSpeed:1500,easing:'easeInOutSine'})

$(".b").click ->
    $("#b").animatescroll({scrollSpeed:1500,easing:'easeInOutSine'})

$(".c").click ->
    $("#c").animatescroll({scrollSpeed:1500,easing:'easeInOutSine'})

$(".d").click ->
    $("#d").animatescroll({scrollSpeed:1500,easing:'easeInOutSine'})

I want to make it like so:

scroll = animatescroll({scrollSpeed:1500,easing:'easeInOutSine'})

$(".a").click ->
    $("body").scroll

$(".b").click ->
    $("#b").scroll

$(".c").click ->
    $("#c").scroll

$(".d").click ->
    $("#d").scroll

but it returns the following error: animatescroll is not defined

War es hilfreich?

Lösung

The reason why it isn't working is because the "scroll" function you're defining is being defined in a variable, while "animatescroll" is a jQuery plugin method.

You can solve this issue the way you want by extending the jQuery object yourself:

$.fn.scroll = ->
    this.animatescroll({scrollSpeed:1500,easing:'easeInOutSine'})

$(".a").click ->
    $("body").scroll()

$(".b").click ->
    $("#b").scroll()

$(".c").click ->
    $("#c").scroll()

$(".d").click ->
    $("#d").scroll()

It should work. However, I don't recommend this because you're adding a method to the jQuery object with hard-coded parameters, and it may interfere with any jQuery plugins you may have added that already add a "scroll" method to the jQuery object.

The way I'd rather go about solving your issue is to make a variable for the parameter and keep using the animatescroll method, like this:

scrollSettings = scrollSpeed:1500, easing:'easeInOutSine'

$(".a").click ->
    $("body").animatescroll scrollSettings

$(".b").click ->
    $("#b").animatescroll scrollSettings

$(".c").click ->
    $("#c").animatescroll scrollSettings

$(".d").click ->
    $("#d").animatescroll scrollSettings

Andere Tipps

You're getting "animateScroll is not defined" because it's only defined as a property of the jQuery object ($). Also, you're defining scroll as the result of calling animateScroll, not as a function which itself calls animateScroll. You could define it like this:

scroll = ($targetEl) ->
    $targetEl.animateScroll({scrollSpeed:1500, easing:'easeInOutsine'})


$(".a").click ->
    scroll $("body")

$(".b").click ->
    scroll $("#b")

$(".c").click ->
    scroll $("#c")

$(".d").click ->
    scroll $("#d")

You can DRY it up a bit further by doing all the click handler setup in a separate function:

makeScroll = (clickSelector, scrollSelector) ->
  $(clickSelector).click -> 
    $(scrollSelector).animatescroll scrollSpeed: 1500, easing: 'easeInOutSine'

makeScroll ".a", "body"
makeScroll ".b", "#b"
makeScroll ".c", "#c"
makeScroll ".d", "#d"
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top