0

I have two html files, index.html and page2.html, I would like to substitute index.html for page2.html when the user clicks on a button using javascript or Jquery. I am trying to load the page into body but when I click the button its makes the page get blank.

function caloriesTopTab(){
  $('#button1').click(function(){
    $("body").load('page2.html');
  });
}

module.exports = caloriesTopTab;
Squexis
  • 97
  • 1
  • 4
  • 12
  • 4
    Why not just use a standard link? As for your actual problem, check the console for errors. There could be any reason for this not working, from not including jQuery to the path to the HTML file being incorrect. – Rory McCrossan Mar 14 '16 at 15:46
  • not familiar with .load but think its misused here.. try window.location = 'page2.html'; ? – JF it Mar 14 '16 at 15:47
  • What error do you get in your console? – putvande Mar 14 '16 at 15:48
  • i believe you don't need to wrap the things in a function? You can use `$(document).ready()` to initiate the button click catch – Woody Mar 14 '16 at 15:50
  • You can see this question as well: http://stackoverflow.com/questions/2238368/how-to-make-a-button-redirect-to-another-page-using-jquery-or-just-javascript – Argiris A Mar 14 '16 at 16:06

1 Answers1

0

You could use the global location.replace function:

$("#button1").click(function() {
    location.replace("/page2.html");
});

Though this is functionally equivalent to using an HTML <a> tag with an href attribute of "/page2.html", and not using javascript at all, which would be the simpler and therefore better way of doing it. If you want the page to load in the background and only to change the DOM when it has loaded, I suppose you could use an AJAX request:

var ajaxRunning = false;
$("#button1").click(function() {
    if (!ajaxRunning) { // don't send two requests at once
        ajaxRunning = true;
        $.ajax("/page2.html", {
            method: "GET",
            dataType: "html"
        }).done(function(html) {
            ajaxRunning = false;
            document.write(html);
        });
    }
});

There's absolutely no real benefit to doing that though (and the cost of greater complexity), unless "page2.html" is a partial HTML file that you're going to use only to update part of the DOM (with the jQuery html or text functions, instead of document.write).

So unless you have a compelling reason to introduce javascript, just use an HTML <a> tag, like so:

<a href="/page2.html">
    <button id="button1">Click me!</button>
</a>
user162097
  • 1,250
  • 11
  • 21