简体   繁体   中英

Why this jQuery animate and append won't work if I use variable?

I'm trying to obtain the width of div.newsticker and trying to use it as variable in animate and append.

However this seems not working. How can I fix?

This is my code.

jQuery(document).ready(function () {
    var width = jQuery("div.newsticker").width()+"px";
}); 

// To get resize notification
jQuery(window).on("resize", function() {
   var width = jQuery(".newticker").width()+"px";
});

function showComments(time){
    var comments = findComments(time);
    if(comments[0]){
        $('.newsticker p').animate({"marginLeft":width,"opacity":".0"}, 600).fadeOut(100);
        $('.newsticker').append("<p style='margin-left:"+width+";opacity:0'>"+comments[0].message+"</p>");
        $('.newsticker p').animate({"marginLeft":"0px","opacity":"1"}, 600);
    }
}

Original code

function showComments(time){
    var comments = findComments(time);
    if(comments[0]){
        $('.newsticker p').animate({"marginLeft":"400px","opacity":".0"}, 600).fadeOut(100);
        $('.newsticker').append("<p style='margin-left:400px;opacity:0'>"+comments[0].message+"</p>");
        $('.newsticker p').animate({"marginLeft":"0px","opacity":"1"}, 600);
    }
}

You need to declare your variable with the correct scope.

var width = '';

jQuery(document).ready(function () {
    width = jQuery("div.newsticker").width()+"px";
}); 

// To get resize notification
jQuery(window).on("resize", function() {
   width = jQuery(".newsticker").width()+"px";
});

function showComments(time){
    var comments = findComments(time);
    if(comments[0]){
        $('.newsticker p').animate({"marginLeft":width,"opacity":".0"}, 600).fadeOut(100);
        $('.newsticker').append("<p style='margin-left:"+width+";opacity:0'>"+comments[0].message+"</p>");
        $('.newsticker p').animate({"marginLeft":"0px","opacity":"1"}, 600);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM