Trenly
Trenly

Reputation: 208

Javascript and Html; get page from URL

I am creating a website for a client and they have given me some very strict limitations. The html must be coded in one document (index.html), with the javascript and css each in their own separate document. They also want me to use Angular or Node only if necessary (it has not been necessary so far).

Since they are requiring multiple “pages” on the website, I am using Javascript to hide or unhide different divs corresponding to each page. I also have the separate divs internally referenced. Therefore, when the maps “page” is open the URL displays as https:\\site.com\#maps . When the page gets reloaded, it ignores the #maps and simply returns to the main “page”.

I have tried using window.location to get the url when the page is loaded, then pass that to my function; however, that has not worked. I also briefly tried messing with cookies to save the page location, but wasnt able to get very far with it.

How can I get the function to load the page I want based on the url?

function openPage(evt, PageName) {
// Declare all variables
var i, tabcontent, tablinks;

// Get all elements with class="tabcontent" and hide them
tabcontent = document.getElementsByClassName("tabcontent");
for (i = 0; i < tabcontent.length; i++) {
    tabcontent[i].style.display = "none";
}

// Get all elements with class="tablinks" and remove the class "active"
tablinks = document.getElementsByClassName("tablinks");
for (i = 0; i < tablinks.length; i++) {
    tablinks[i].className = tablinks[i].className.replace(" active", "");
}

// Show the current tab, and add an "active" class to the link that opened the tab
document.getElementById(PageName).style.display = "block";
evt.currentTarget.className += " active";

//set the page cookie
var expiry = new Date();
expiry.setTime(expiry.getTime()+600000);
expires = "; expires=" + expiry.toUTCString();
document.cookie = "Page=" + PageName + expires + " ; path=/";
}

Upvotes: 0

Views: 124

Answers (2)

xxxmatko
xxxmatko

Reputation: 4142

Well, each div element has to have the id attribute, this attribute identifies the page/div and will be set as value for the window.location.hash.

Than handle all click events which trigger the page change, for instance all a elements with href attribute set to these ids.

Then create function which will show/hide the desired page, and call this method when the whole html page is loaded.

Here is an example using jQuery (if you want there is no need to use jQuery, you can do it with vanilla javascript as well):

$(function() {
	// Method wich show/hide pages
	function showpage(target) {
		// Target is the id of the page div
		var $target = $(target);
		
		// If there is not any page with that id do nothing
		if(!$target.length) {
			return;
		}
	
		// Hide all pages
		$(".page").css("display", "none");
		
		// Show the target page
		$target.css("display", "block");
		
		// Update the window has
		window.location.hash = target;
	}

	// Handle clicks which show pages
	$(document).on("click", "a[href^='#']", function (e) {
		e.preventDefault();
		showpage($(this).attr("href"));
	});

	showpage(window.location.hash);
});
.page {
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
  <li>
    <a href="#page1">page1</a>
  </li>
  <li>
    <a href="#page2">page2</a>
  </li>
  <li>
    <a href="#page3">page3</a>
  </li>
  <li>
    <a href="#page4">page4</a>
  </li>
</ul>

<div id="page1" class="page">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus interdum velit pretium porttitor aliquam. Proin a lectus nec ligula laoreet tempor. In ornare volutpat velit, non semper mauris accumsan nec. Aliquam nibh nisi, pellentesque eu mauris eu, fringilla faucibus leo. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum pretium, tortor eget scelerisque luctus, enim quam elementum diam, ac varius elit tortor eu tortor. Morbi molestie massa nec aliquam fringilla. 
</div>
<div id="page2" class="page">
Maecenas sagittis convallis turpis, sed fermentum magna porttitor eget. Aenean et lectus eu velit interdum aliquet. Duis faucibus sollicitudin iaculis. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent suscipit pulvinar felis, at fermentum dolor ultrices non. Maecenas malesuada urna lorem, mollis lobortis nisi semper et. Quisque ac tellus interdum, hendrerit nisl eu, feugiat ante. Nullam tincidunt ex non metus venenatis suscipit. Duis rutrum convallis erat, quis ultrices nunc efficitur sed. Donec lacinia tellus eu neque tempus, eu bibendum odio sollicitudin. Nullam convallis ligula vitae sapien tristique, eget ullamcorper risus pulvinar. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Donec tincidunt, sapien vel eleifend laoreet, tortor dolor ultrices est, consequat suscipit neque metus a velit. Maecenas cursus nec arcu et varius. Nulla ex lorem, mollis eu risus quis, molestie dapibus nisl. Maecenas vel imperdiet mauris, ut pretium odio. 
</div>
<div id="page3" class="page">
Donec mi mi, placerat tincidunt justo sit amet, facilisis congue sapien. Nunc lacinia lobortis turpis ac rhoncus. Donec tempus elit vitae pharetra congue. Nam at dolor at metus hendrerit pharetra nec et velit. Morbi iaculis ipsum non finibus hendrerit. Nunc eget ex non augue feugiat venenatis a sit amet nisl. Vestibulum elementum ipsum non enim pulvinar malesuada. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis et purus vitae libero lobortis gravida et eu lectus. Aenean dignissim molestie ante a iaculis. 
</div>
<div id="page4" class="page">
Pellentesque iaculis diam a condimentum aliquam. Integer vestibulum interdum ligula, quis tempus felis aliquam at. Ut vel tincidunt purus, quis convallis ipsum. Pellentesque massa velit, varius gravida purus nec, consectetur suscipit nibh. Vivamus vel dui sit amet magna condimentum sodales ac a urna. Sed viverra, dolor sit amet facilisis commodo, tortor massa efficitur neque, sit amet sollicitudin lectus augue sed est. Nulla dapibus facilisis magna, vestibulum maximus dui gravida convallis. Sed sit amet tellus non velit tincidunt mollis vitae vitae purus. Donec sed molestie lacus. Morbi condimentum sapien nec odio scelerisque bibendum. 
</div>

Upvotes: 1

Rickard Elim&#228;&#228;
Rickard Elim&#228;&#228;

Reputation: 7591

Use the onload property on your body tag:

<body onload="pageLoaded(window.location.hash)">

https://www.w3schools.com/jsref/event_onload.asp

Upvotes: 0

Related Questions