efong5 efong5 - 4 months ago 7
jQuery Question

What issues interfere with use of a jquery element stored in a variable?

Context: I am trying to hack together a script that detects a session variable and hides a UI element when the variable

!== null
.

This is the script:

var userid = $('#userid').attr('data-id');
var signUpContainer = $('#sign-up-container');

if (userid != null) {
$('#sign-up-container').css('display','none');
};


This script works perfectly fine. However, when I use the variable instead:

if (userid != null) {
signUpContainer.css('display','none');
};


nothing happens. Any reasons why this is the case?

Note: I've never run into this issue before while storing a jquery object in a variable, and it seems to only occur when trying to change CSS.

Answer

This problem must be somewhere else in your code.

You should be able to store references to jQuery objects in variables without any issues. See the following example which works perfectly fine:

var userid = $('#userid').attr('data-id');
var signUpContainer = $('#sign-up-container');

if (userid != null) {
    signUpContainer.css('display','none');
};
#sign-up-container {
   background: yellow; 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id='userid' data-id='test'></div>
<div id='sign-up-container'>Signup Container</div>

Comments