2

How to use a var value and pass it to the window.open url? I'm really no good at this, so the simpler the better. Thank you very much!

<script>
    if (condition) {
        var URL = "http://www.url.com";
    } else {
        var URL = "http://www.url2.com"
    }
</script>
<div id="Banner" data-responsive="225h" onclick="window.open('URL','new_window');">

3 Answers 3

3

Notice there's no quotes around the URL variable in window.open. Also to be more concise, I've moved the var URL portion out of the if/else logic.

<script>
    var URL;
    if (condition) {
        URL = "http://www.url.com";
    } else {
        URL = "http://www.url2.com"
    }
</script>
<div id="Banner" data-responsive="225h" onclick="window.open(URL,'new_window');">

An even better solution would be to get rid of your inline click handlers altogether like so:

<div id="Banner" data-responsive="225h"> ... </div>
<script>
    function openWindow() {
        var URL;
        if (condition) {
            URL = "http://www.url.com";
        } else {
            URL = "http://www.url2.com"
        } 
        window.open(URL,'new_window');
    }

    var banner = document.getElementById('Banner');
    banner.addEventListener('click', openWindow, false); //using addEventListener for brevity
</script>
Sign up to request clarification or add additional context in comments.

2 Comments

You might want to mention moving var outside the if. That change may be overlooked.
Added an even better example.
0
<script>
  function a() {
   if (condition) {
     var URL = "http://www.url.com";
   }
   else {
    var URL = "http://www.url2.com"
   }
   window.open(URL);
  }
</script>
<div id="Banner" data-responsive="225h" onclick="a();">click me</div>

Alternative solution

Comments

0

If the point of your question is to have a clickable, formatted html area, You can use an anchor and have nested html elements inside it instead.I see this much cleaner.

<a href="http://www.google.com" target="_blank">
<p> I am an element inside an anchor</p>
<!-- you can put an image here instead -->
</a>

http://jsfiddle.net/CpXVB/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.