Kelvin Barsana Kelvin Barsana - 7 months ago 7
Javascript Question

Assign variable value as variable name

the problem is i want to shorten my code by calling a variable using other variable's value

long working version:

var russia = new Array('15')
var switzerland = new Array('5')

$('.country').mouseover(function(){
switch(this.id){
case 'russia':
active_country_lift(this.id,russia[0])
break
case 'switzerland':
active_country_lift(this.id,switzerland[0])
break
}
})


it will get the id of mouseovered then check if it matched one of the variable by using switch

what i want to obtain is something like this:

var russia = new Array('15')
var switzerland = new Array('5')

$('.country').mouseover(function(){
active_country_lift(this.id,this.id[0])
})


of course the above code wouldn't work but is there a workaround for this?

UPDATE: Arun's answer worked and ill accept it soon and as for the comments requesting for the full code, here's a chunk of it after i applied Arun's

var countries = {
russia: ['-15px'],
switzerland: ['-5px']
}

$('.country_inactive').mouseover(function(){
active_country_lift(this.id, countries[this.id][0])
})

function active_country_lift(country, country_top){
if(!$('#'+country+'_active').hasClass('active')){
$('#'+country+'_active').stop().fadeIn(100).animate({
'top' : country_top
}, 200)
$('#'+country).stop().fadeOut(100)
}
}


it will be used for a world map, feel free to make any suggestions for making it more dynamic

Answer

You can store the country info in an object like a key value pair, then use bracket notation to access it dynamically

var countries = {
  russia: new Array('-15px'),
  switzerland: new Array('-5px')
}

$('.country').mouseover(function() {
  active_country_lift(this.id, countries[this.id][0])
})

If you don't have multiple values then

var countries = {
  russia: '-15px',
  switzerland: '-5px'
}

$('.country').mouseover(function() {
  active_country_lift(this.id, countries[this.id])
})
Comments