treehouse : what would you like to learn today?
Web Design Web Development iOS Development

jquery external and internal button hyperlink

  • how can i make it so that whenever a person clicks on the the first button it opens in a new window also how can i make it so that when a user clicks the second button that it opens in the same tab or window. i want to achieve this with jquery that being said i don't want to write any inline javascript otherwise if that was the case i wouldn't have posted the question i know how to achieve this using inline javascript but i want to do it using external js file and jquery.

    open in new window

    <button class="button cf-button preview-bt" role="button" type="button" href="#">
    <span class="button-content"> Preview </span>
    <span class="button-icon"> </span>
    </button>

    open in same window



    open in new window

    <button class="button cf-button preview-bt" role="button" type="button" href="#">
    <span class="button-content"> Preview </span>
    <span class="button-icon"> </span>
    </button>
  • Well, I am not sure why you don't just use anchor tags but if you must here is the solution:

    1. add an href attribute and set it to wherever you want the button to goto...
    2. add a "target" attribute, if you want it to open in the same page set it to "_self" if you want it to open in a new window set target to "_blank"

    Le Modified Buttons:

    <button class="button cf-button preview-bt" role="button" type="button" href='http://www.css-tricks.com' target="_self">
    <span class="button-content"> Preview New Window </span>
    <span class="button-icon"> </span>
    </button>
    <button class="button cf-button preview-bt" role="button" type="button" href='http://www.google.com' target="_blank">
    <span class="button-content"> Preview </span>
    <span class="button-icon"> </span>
    </button>


    Le jQuery

    $("button").click(function() {
    var url = $(this).attr('href'); // Get the URL to travel to
    var target = $(this).attr('target'); //Are we opening in a new window or the current window?
    window.open(url, target); //Open the window
    });