I have a snippet of JQuery code that do some bar scrolling.
Since I have three, four, … n bar to slide into my PHP page, I assign them dinamically an id and pass it to JQuery for be sure that my snippet slide the correct bar on a mouseOver event.
That’s the snippet of code that do the “inizialization” of my scrolls
(function($){
$.fn.horizontalScroll = function(options) {
var rid = arguments[0];
var oid = arguments[1];
var defaults = { };
var options = $.extend(defaults, options);
return this.each(function() {
var horiz_scroll = new dw_scrollObj($(this).attr('id'), $(this).children().attr('id'), $(this).children().children().attr('id'));
horiz_scroll.setUpScrollbar("dragBar_"+rid+"_offer_"+oid, "track_"+rid+"_offer_"+oid, "h", 1, 1);
horiz_scroll.setUpScrollControls('scrollbar_'+rid+'_offer_'+oid);
As you can see, "dragBar_"+rid+"_offer_"+oid dinamically concatenates my id(s) to other string part.
That’s fine and all goin’ well, except when my oid became something like -1
In that case I have an error that says
identifier starts immediately after numeric literal
That’s confuse me, because i’ve read on StackOverflow some questions like this (just a random one) and I expect that behaviour for all concatenation that involves number.
That the snippet of code where all “breaks”
this.timerId = setInterval(this.animString + ".scroll()", 10);
Where this.animString is "dw_scrollObj.col.horiz_container_outer_55_offer_-1" while in other case (where it works) is "dw_scrollObj.col.horiz_container_outer_62_offer_234"
Anyone can explain me why this happen?
You are trying to access a global variable named
dw_scrollObj.col.horiz_container_outer_55_offer_-1. Some browsers will make all elements accessible by theirIDlike that, but it’s not recommended.The reason it doesn’t work in your specific case is that what you’ve written is not a valid javascript variable name. Your attempt to access a variable will be interpreted as
If you would instead access your object by
or
you would not have this same problem.
For your
setIntervalcode, that would meanor preferably
If your code is in a loop, where
animStringwill change over time, inside the context, you will need to create a new closure: