user1017882
user1017882

Reputation:

JQuery - fadeIn using variable instead of id?

This code works:

$(contentDiv).fadeIn("slow");

This does not:

var elementName = 'contentDiv';
$(elementName).fadeIn("slow");

No fade effect appears.

I'm about to feel like an idiot with this solution I know but I can't work it out.

Upvotes: 0

Views: 2383

Answers (6)

Salman Arshad
Salman Arshad

Reputation: 272266

This code works:

$(contentDiv).fadeIn("slow");

It should not work unless you are using Internet Explorer. IE has a nasty habit of creating variables for HTML elements that have an ID. (EDIT: chrome seems to do that too).

The connect way is:

var elementName = "contentDiv";
$("#" + elementName).fadeIn("slow");

Upvotes: 1

Sameera Thilakasiri
Sameera Thilakasiri

Reputation: 9508

var elementName = '#contentDiv';
$(elementName).fadeIn("slow");

# is the reason.

Upvotes: 1

Sarfraz
Sarfraz

Reputation: 382816

contentDiv is not a tag/element. You are forgetting to specify an id or class to your selector:

var elementName = '#contentDiv';

Or

var elementName = '.contentDiv';

depending on whether you use a class or id for your div(s).

Upvotes: 1

HandiworkNYC.com
HandiworkNYC.com

Reputation: 11114

You need to specify whether 'contentDiv' is a class or id

var elementName = '.contentDiv';
$(elementName).fadeIn("slow");

OR

var elementName = '#contentDiv';
$(elementName).fadeIn("slow");

Upvotes: 2

James Allardice
James Allardice

Reputation: 166021

You need to prepend your string with the rest of the selector. If contentDiv is an id, that would be a #:

$("#" + elementName").fadeIn("slow");

If it is actually a value of a name attribute you would need to insert it into an attribute selector:

$("[name='" + elementName + "']").fadeIn("slow");

If contentDiv is something else (a class perhaps), you need to change the selector appropriately. The section on selectors in the jQuery docs would be a good place to start.

What you currently have will look for an element of type "contentDiv", which is not what you want:

<contentDiv>This is an invalid element...</contentDiv>

Upvotes: 1

jabclab
jabclab

Reputation: 15052

If "contentDiv" is the name of your element then you need to use:

$("[name=" + elementName + "]").fadeIn("slow");

If it's the id then you need to use:

$("#" + elementName).fadeIn("slow");

Upvotes: 1

Related Questions