akano1
akano1

Reputation: 41614

variable scope in jquery

I'm trying to access the value of a variable that is set inside a .click function outside of the function but I'll get the error, can anyone please tell me what I'm doing wrong?

var id;
var currentPosition;
var slideWidth = 368;
var slides;
var numberOfSlides;

$('#accordion_catering h3').click(function() {
    id = $(this).attr('id');
    $('#' +id+'_gallery').show();
    //alert(id);//works
});
alert(id); // is undefined

// Because id is undefined these don't work .

slides = $('.' + id + '_slide');
numberOfSlides = slides.length;

Upvotes: 0

Views: 140

Answers (3)

Mark Schultheiss
Mark Schultheiss

Reputation: 34168

var id;  
var currentPosition;  
var slideWidth = 368;  
var slides;  
var numberOfSlides;  
$(document).ready(function() {  
   $('#accordion_catering h3').click(function() { 
        id = $(this).attr('id'); 
        $('#' +id+'_gallery').show(); 
        //alert(id);//works 
        slides = $('.' + id + '_slide'); 
        numberOfSlides = slides.length; 
    }); 
    $('#accordion_catering h3').trigger('click');
    alert(id); // is defined 
)};

So, basically, do not access id until this event has fired, it will then be set.

Upvotes: 0

user57508
user57508

Reputation:

click did not occure yet, so id is not set ... it's not about variable-scopes, more about events and their handlers :)

as you added a cmt, i adapted my solution as following:

var currentPosition;
var slideWidth = 368;
var slides;
var numberOfSlides;
$(document).ready(function() {
    var element = $('#accordion_catering h3');
    element.click(function() {
        var id = $(this).attr('id');
        DisplayGallery(id);
    });
    element.trigger('click'); // maybe you want to trigger it
});
function DisplayGallery(id) {
    $('#' + id +'_gallery').show();
    slides = $('.' + id + '_slide');
    numberOfSlides = slides.length;
}

Upvotes: 3

Philippe Leybaert
Philippe Leybaert

Reputation: 171774

id will only be set when the click event handler is run at least once, because you're setting the id variable inside the event handler

Upvotes: 3

Related Questions