2

I'm trying to make it so that my button will open a url in a new tab.

I can get it to work using window.location.href, but the url doesn't open in a new tab that way.

I'm using jQuery and Javascript, and the code itself is inside of a larger jQuery function.

$('#code').click(function(){
    window.location.href = 'http://www.example.com'
});

The button has no href attribute on page load.

<button id="code" type="submit" class="btn btn-success" style="width:400px;"><span class="glyphicon glyphicon-download"></span> Generate Code</button>

I've tried using .attr and .prop though it hasn't worked either. I'm kinda new to this stuff so I could've just done something wrong.

I'm open to either adding an href to the button or using the .click function or whatever, I just need to get this to open to a new tab.

Edit:: Ok, more explanation.

On Page load, the button onclick starts a timer that increments a progressbar. After the progressbar is done I want the button to open a link.

2
  • 2
    why not just make an anchor tag a button by using the btn css class. Then just use target="_blank" attribute. Commented Jan 22, 2014 at 21:15
  • 4
    JavaScript is a great tool, but you should avoid it where it's not necessary. Use <a href="..." class="btn"> Commented Jan 22, 2014 at 21:24

2 Answers 2

15

You could do this:

<a href="http://www.example.com" target="_blank" id="code" type="submit" class="btn btn-success" style="width:400px;"><span class="glyphicon glyphicon-download"></span> Generate Code</a>

I converted the button to an a tag and added target="_blank" to open the link in a new tab.

Sign up to request clarification or add additional context in comments.

Comments

1

This will open the url in a new window:

$('#code').click(function(){
window.open("http://www.w3schools.com");
});

http://www.w3schools.com/jsref/met_win_open.asp

1 Comment

Thanks! I have no idea why, but when I was using the open function it wouldn't work. Just what I was looking for!

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.