Reputation: 245
I am building a jquery slider, and i am having troubles with one global variable. I can not use it as local in my case. I am using multiple sliders on one page so this global variable EndPosition should be different from slider to slider.
$.fn.slider = function(id) {
var SliderID = id;
EndPosition = (VisibleWidth - TotalWidth); //End position for sliding
Is there a way to pass an id to variable name, something like EndPosition+id so i can use it like that in other parts of code, for example here
if (NewPosition <= EndPosition+id){
RightNav.addClass('disabled');
}
Upvotes: 0
Views: 102
Reputation: 3287
A cleaner way (IMO) :
$.fn.slider = function(...) {
// ...
$(this).data('end-position', visibleWidth - totalWidth);
// ...
};
So if you did
$('.slider').slider(...);
You can access to the end-position
variable like this
$('.slider').data('end-position');
EDIT:
If you need to find a slider's end position by id, you can do this this way :
<div class="slider" data-id="1"></div>
<script type="text/javascript">
$(document).ready(function() {
$('.slider').slider(...);
... = $('.slider[data-id=1]').data('end-position');
});
</script>
Upvotes: 1
Reputation: 144689
I'd suggest using an object and bracket notation:
var positions = {
'endPosition1': 'foo',
'endPosition2': 'bar'
}
var value = positions['endPosition' + id];
In case that your variables are global, you can access them like other properties but this time those are properties of the global window
object:
window['EndPosition' + id];
If the id
s are numeric you can also you a simple array:
var positions = ['foo', 'bar'];
positions[id];
positions[id - 1]; // ?
Upvotes: 2
Reputation: 209
yes you can use json array you can do something like this :
var sliderObject = [
{ "EndPosition":VisibleWidth - TotalWidth },
{ "ID": id },
];
And then just check ::
NewPosition <= sliderObject [EndPosition][0]
Take a look at : http://www.w3schools.com/json/json_syntax.asp
Upvotes: -1
Reputation: 281425
It would be cleaner to use an object to contain your end positions, rather than using multiple global variables:
var EndPositions = {};
// ...
EndPositions['id_one'] = 10;
EndPositions['id_two'] = 20;
// ...
if (NewPosition <= EndPositions[id]){
RightNav.addClass('disabled');
}
Upvotes: 2
Reputation: 18344
Right, you can with:
window["EndPosition" + id]
so you'd have:
if (NewPosition <= window["EndPosition" + id]) ...
window
is the container for all global vars.
Cheers
Upvotes: 0