Arafat
Arafat

Reputation: 143

Can't work JavaScript page loading function in html

I want to load a new page when I click one of the menu from sidebar. But the JavaScript load function doesn't work.

$(document).ready(function(){
  $( 'button' ).click(function() {
    $('#load').load('page1.html');
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="load"></div>
<button>Click to load a new page</button>

Please need help.

Upvotes: 0

Views: 246

Answers (5)

sdn
sdn

Reputation: 21

Try to install any web server and try it.. it must work

Upvotes: 0

dmakovec
dmakovec

Reputation: 68

A couple of things -

  1. Place your JS after your HTML to ensure all elements with the referenced IDs are loaded, or your code may not work.

  2. You don't even need JQuery to do what you want. See the following snippet which uses the fetch() API built into all modern browsers (note you'll get an error displayed if you run the snippet below on this page because page1.html isn't available on StackOverflow)"

<html>
	<head>
		<title>Hello</title>
	</head>
	<body>
		<div id="load" ></div>
		<button id="clickme">Click to load a new page</button>
		<script type="text/javascript">
			(function() {
	document.getElementById("clickme").onclick = function() {
		fetch("page1.html")
			.then(function(response) {
				response.text().then(function (text) {
					document.getElementById("load").innerHTML = text;
				})
			})
			.catch(function(e) {
				document.getElementById("load").innerHTML = `Error loading: ${e.message}`;
			})
	}
}());
		</script>
	</body>
</html>

Upvotes: 0

Pravin Vavadiya
Pravin Vavadiya

Reputation: 3207

Your Jquery code is correct. check in console error i think your page1.html is not found.

So, set correct page1.html file path.

If Page1.html path is correct then try this. it's work for me in chrome.

$(function() {
    $( 'button' ).on('click', function() {
        $('#load').load('page1.html');
    });
});

Html code.

<div id="load"></div>
<button>Click me</button>

Upvotes: 1

Bhaskararao Gummidi
Bhaskararao Gummidi

Reputation: 1635

Try This

$(document).ready(function(){
  $( 'button' ).on('click', function() {
    $('#load').load('page1.html');
  });
});

Add button type button to your button tag

<button type="button">Click to load a new page</button>

Upvotes: 0

slon
slon

Reputation: 1030

I have moved javascript code to the end of page and it works:

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>load demo</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>

<div id="load"></div>
<button>Click to load a new page</button>
<script>
   $('button').click(function() {
        $('#load').load('page1.html');
    });
</script>
</body>
</html>

Upvotes: 0

Related Questions