venuxv venuxv - 1 month ago 8
HTML Question

Redirect to (currenturl)/example.html onclick with JavaScript

I'm trying to have my location change from 'currentUrl' to 'currentUrl/somePage.html' when you click a button.

It's important that the code isn't reliant on having a hard-coded url. Instead, it should grab the current url that the user is sitting at and append the value of '/somePage.html' to the end of it.

I've done some looking and found that window.location.href will return my current url location, and that window.location will redirect me to a new one. However, when I try putting these together, I'm getting a "function not defined" error when I click my buttons.

My code looks something like this...

HTML:

<button class="btn btn-default" onclick="redirectToPage()">Some Page</button>


JS:

$(function () {

function redirectToPage() {
var url = window.location.href;
window.location(url + "/somePage.html");
}
});


Thank you!

Answer

If you're going to use jQuery then you should use all of it's capabilities:

(that and I would never recommend inline javascript)

html:

<button class="btn btn-default js-do-redirect">Some Page</button>

jQuery:

$(document).ready(function(){
  $('.js-do-redirect').on('click', function(){
    var url = window.location.href;
    window.location = url + "/somePage.html";
  });
});

or if you want to make it reusable:

html:

<button class="btn btn-default js-do-redirect" data-redirect-to="/somePage.html">
  Some Page
</button>

jQuery:

$(document).ready(function(){
  $('.js-do-redirect').on('click', function(){
    var url = window.location.href;
    var page = $(this).data('redirect-to');
    window.location = url + page;
  });
});
Comments