Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Passing variables to URLs

So I'm still very new to JavaScript, so forgive my ignorance in advance. I have a function that opens a browser window with certain parameters. I also have a list with buttons. I have NO clue how to make each button (linked to different web pages) create a new browser window with the same parameters, but different url. Here's some example code to help me explain:

function myFunction() {
window.open("/sites/rdecomsgs/SGSi/Picture%20Storage/SPMS_Page_1.jpg", "_blank", "toolbar=yes, scrollbars=yes, resizable=yes, top=, left=500, width=1100, height=600");
}
<ul>
<li><a onclick="myFunction()"></a>Btn 1</li>
<li><a href="/sites/rdecomsgs/SGSi/Picture%20Storage/SPMS_Page_2.jpg"></a>Btn2</li>
<li><a href="/sites/rdecomsgs/SGSi/Picture%20Storage/SPMS_Page_3.jpg"></a>Btn3</li>
</ul> 

I'd like to apply myFunction to each list item, but where it opens THAT list item's specific url.

Thanks in advance!

Jesus Mendoza
Jesus Mendoza
23,288 Points

Hey Threman, to make a link open in a new window just add target="_blank" to your a element

<li><a href="/sites/rdecomsgs/SGSi/Picture%20Storage/SPMS_Page_2.jpg" target="_blank">Btn2</a></li>

2 Answers

Jesus Mendoza Thanks for replying, but I'm asking something different.

I'm asking, how do I get Btn2 to open up /SPMS_Page_2.jpg and how do I get Btn3 to open up /SPMS_Page_3.jpg by just applying myFunction?

The URL in myFunction is currently /SPMS_Page_1.jpg. When I click on Btn1, it opens that URL. I'm asking, how do I get that URL to change based on the button a user clicks on?

Jesus Mendoza
Jesus Mendoza
23,288 Points
<ul>
<li><a onclick="myFunction('SPMS_Page_1.jpg')">Btn 1</a></li>
<li><a onclick="myFunction('SPMS_Page_2.jpg')">Btn 2</a></li>
<li><a onclick="myFunction('SPMS_Page_3.jpg')">Btn 3</a></li>
</ul> 
function myFunction(url) {
window.open("/sites/rdecomsgs/SGSi/Picture%20Storage/" + url, "_blank", "toolbar=yes, scrollbars=yes, resizable=yes, top=, left=500, width=1100, height=600");
}

You can do that adding properties to the a element though

Yes!!! Thanks Jesus Mendoza