/    Sign up×
Community /Pin to ProfileBookmark

Beginner question

Hi there!

I’m a beginner in JS and I have this code line:

[CODE]
var container = $(“#popup_window”);
[/CODE]

As you can see, the name of the popup window is hardcoded. How do you write that code line so that I can use a variable name instead? Something like this:

[CODE]
var variable = ‘popup_window’;
var container = $(variable);
[/CODE]

Obviously, this doesn’t work.

I need this for a small script that hides a DIV element when you click outside of it. The problem is that I have multiple DIVs and I need to make this code work with all of them. To do that, I have to replace #popup_window with a variable. Here’s the script:

[CODE]$(document).mouseup(function (e) {
var container = $(“#popup_window”);
if (!container.is(e.target) && container.has(e.target).length === 0) {
hide_popup();
}
});[/CODE]

Thank you!

Alex

to post a comment
JavaScript

2 Comments(s)

Copy linkTweet thisAlerts:
@SempervivumJan 10.2016 — Your approach is fairly correct, the only problem is that the variable is missing the "#". This is correct:
[CODE]var variable = '#popup_window';
var container = $(variable);[/CODE]
Copy linkTweet thisAlerts:
@alexander2000authorJan 10.2016 — Your answer made me try something that I didn't try before:

[CODE]var container = $("#" + variable);[/CODE]

It's working fine now.

Thank you!

Alex
×

Success!

Help @alexander2000 spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 6.1,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...