I need to update my page using Anchor (#) in URL - javascript

index.php
<html>
<head>
<title>My Title</title>
<script type="text/javascript">
function getLink(data) {
document.getElementById("box").innerHTML="This is "+data;
}
</script>
</head>
<body>
Home<br />
Profile<br />
Message<br />
Setting<br />
<hr />
<div id="box"></div>
</body>
</html>
Output
Home
Profile
Message
Setting
This is Home
As the code says my Div contents updated when i click any of the link but the problem is that when user goes back by clicking Back Button of Browser the content of my Div donot changes.
I want that either user Goes Back, Goes Forward or he directly puts the path in the address bar www.*****/index.php#profile the content of my Div should be change.
Note
I used document.location.hash to get the value of hash like this :
<head>
<script>
var hashValue=document.location.hash;
alert(hashValue);
</script>
</head>
but it works only when user goes back and then refresh the page
Plz help me how can i achieve this :(

You need to use hashchange event:
function hash_changed() {
var data = document.location.hash.substr(1);
var box = document.getElementById("box");
if (data) {
// inner page
box.innerHTML="This is " + data;
}
else {
// homepage
box.innerHTML = "";
}
}
window.onhashchange = function () {
hash_changed();
};
window.onload = function () {
hash_changed();
};
Also when you are using hashchange event, there is
no need to set onclick for your links:
Home
Profile
Message
Setting
When user click on a link, the hash automatically changes (with href attribute of link),
and hashchange event get fired.
Check DEMO here.
First Time
When a user come to your page for the first time with a hash:
http://fiddle.jshell.net/B8C8s/9/show/#message
We must show the wanted page (message here), so we must run hash_changed() function
we declare above, at first time. For this, we must wait for DOM ready or window.onload.

Check the HTML5 history API. It allows you to work with the browser history
HTML5 history api

$(window).on('hashchange', function() {
alert(location.hash);
});
or window.onhashchange event if you don't want to use jQuery

If you're going to be using AJAX, you'll really want to look into using jQuery instead of raw javascript unless your intention is educational. jQuery is just a mainstay of the web now.
If you must use those hashes...
Use jQuery Special Events, and use the hashchange event:
<a href='#home'>Home</a>
Script:
$(window).on('hashchange', function() {
$('#box').html("This is "+event.fragment);
});
However, for your scenario...
You don't need to use those # values at all as you're passing the values in your function arguments anyway according to the code you provided, just do this:
Home<br />
Alternatively (and preferably, as you're using AJAX according to the tags) you can use jQuery and its builtin selector click events which use Event Listeners:
<a href='javascript:void();' class='divLink' id='home'>Home</a><br/>
Script is this easy:
$('.divLink').click(function(){
$('#box').html("This is "+$(this).id());
}

Related

Trigger Click event of anchor tag using jQuery

I am trying to trigger the click event of an a tag using jQuery and have seen many other Stack Overflow posts about this, but can't figure out why my replications of any of them are not working. My HTML is shown here:
<c:url var="link" value="/hardwareItems" />
<a href="${link}" id="goToHardwareItems">Go
to items</a>
And then here is my jQuery/JS:
$("#form").on("submit", function() {
if (confirm("Add hardware items?")){
$("#goToHardwareItems").trigger('click');
}
else {
window.location.href = "/home";
}
});
What I have is not working though, but when I actually click on the link, I am indeed taken to the page. So the problem is that the event is simply not triggering, even though I am also getting into the if statement. What am I doing wrong?
You can read the value of href and redirect. You are already doing so.
$("#form").on("submit", function () {
// Determine where to go based on user's response
var link = confirm('Add hardware items?') ? $('#goToHardwareItems').attr('href') : '/home';
window.location.href = link;
});

AJAX back button

I've been reading about history.pushState and popstate but for a web-page that's populated with mostly AJAX requests (say a book store that allows users to add items to a cart), is there a function with the history object or something similar, that can rewind these additions?
A simpler representation of this is in the below example. A user clicks on a div and "Shown" appears in the respective div. Below these divs is the text, You have selected [detail]. This changes with respect to the selection and triggering the popState changes the text in the right way.
But the divs still have "Shown". Is there a way to remove these in order as they were added similar to how the line of text changes, or do I have to create a separate function to take care of this - which would be the opposite of the function that added "Shown" to the div?
I've added some function that I've edited in to achieve the above but I just don't like how hacky it is.
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div class='name'></div>
<div class='age'></div>
<div class='sex'></div>
<p>You have selected <span>no color</span></p>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
</script>
<script>
$('div').on('click', function() {
var detail = $(this).attr('class');
showDetails(detail);
doPushState(detail);
});
function showDetails(detail) {
var classDeets = '.'+detail
$(classDeets).text("Showing " + detail);
$('p span').text(detail);
}
function doPushState(detail) {
var state = { selected : detail },
title = "Page title",
path = "/" + detail;
history.pushState(state, title, path);
}
function removeDetails(detail) {
var classDeets = '.'+detail
$(classDeets).text("");
}
function checkState(detail) {
var temp = document.getElementsByClassName(detail)[0].innerHTML;
if(temp.length == 0){
showDetails(detail);
}
else{
removeDetails(detail);
}
}
$(window).on('popstate', function(event) {
var state = event.originalEvent.state;
if (state) {
checkState(state.selected);
}
});
</script>
I'm not sure exactly what your use case is, but I immediately think of ajax loaded report and list pages that I do. I encode the options for the report after a "#". It makes the browser buttons work as intended for updating url based and it makes it linkable to others. You then just need to poll the # encoded data to detect changes and update accordingly. Since you use the # (in page link) it doesn't trigger a page load to the server. You just have to make sure that if you use encoded hash data that you don't use in-page links for page navigation. If this sounds like an option, let me know and I can post some helper code for setting it up.
Without more context, it's tough to rewrite your code. That said, you need to use history.replaceState() instead of history.pushState().
history.replaceState() modifies the state of a history entry. From MDN: "replaceState() is particularly useful when you want to update the state object or URL of the current history entry in response to some user action."

JavaScript Run full A href command

I have a website where there is a side menu filled with links. On top of that are some Next and Prev buttons for the user to switch between the menus of links.
I want to change this so that the menu will automatically change after x amount of time.
I thought something like this would do it:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function delayer(){
window.location = "http://www.google.com" }
</script>
</head>
<body onLoad="setTimeout('delayer()', 1000)">
</body>
</html>
Basically, instead of opening google, I want the page to run the "Next" button which is represented by:
<div class="navBtns mar9 s3">
<span></span>
<span></span>
</div>
Any idea on how to do this? Thanks!!
If you'd like to "click" the next button, then you can do that programatically with JS.
var nextbutton = document.getElementsByClassName('next');
nextbutton.click();
Getting element by class like that only works on post-IE8 browsers.
<span></span>
This hyperlink does nothing by itself. Somewhere on the site, there is a javascript function bound to the click event of this link. You need to either trigger a click event on the link, or call the javascript directly.
Without seeing the rest of the javascript / knowing what frameworks are in use on the page, it's impossible to give a more precise answer.
-- EDIT --
Based on your comment, you may be able to do something along these lines:
<script type="text/javascript">
setTimeout(function() {
$('#page_HOME .slider .next').click();
}, 1000);
</script>
As long as those hyperlinks are contained inside the slider element, the above code will trigger a change in your side menu after 1000 milliseconds
You could find the HREF of the link you want based on the class name of the link, using plain old JS.
window.location = document.querySelector(<link class name>).getAttribute("href");
This will redirect the browser to whatever the href attribute is set to.
If you wanted to keep a function like you have, you could use this:
function delay(link, time) {
setTimeout(function() {
window.location = document.querySelector("." + linkClass).getAttribute("href");
}, time);
}
Then to use it, just say:
delay("next", 5000); // go to the href of the link with the class "next" after 5 seconds.

Change history using hash doesn't trigger a function neither changing with back button

I'm changing the background of some Links using JavaScript:
$(document).ready(function(){
$("#home").click( function(){
$("body").removeClass("bg2 bg3").addClass("bg1");
});
$("#link1").click( function(){
$("body").removeClass("bg1 bg3").addClass("bg2");
});
$("#link2").click( function(){
$("body").removeClass("bg1 bg2").addClass("bg3");
});
});
Bg1,2,3 are css classes of background (bg images). I prevent refresh button (to save BG) with hash:
var x = location.hash;
if (x==="#link1")
{
$ ("body").removeClass("bg1 bg3").addClass("bg2");
}
else if (x==="#link2")
{
$ ("body").removeClass("bg1 bg2").addClass("bg3");
}
});
It work but if i click on back button it doesn't change the background to previous link background. Is it possible to fix it except web storage/session storage? With hash or somethink like this?
When you hit the back button of your browser, the page will not reload because you are using the hash, this means to the browser that you want to move to a different anchor.
To proper manipulate the history stack you need to use the freaking awesome History API
To fix your problem you need to intercept the event triggered when your history stack change.
<html>
<head>
<script type="text/javascript" src="../lib/jquery.1.9.2.js"></script>
</head>
<body onload="checkHash();">
testing hash stuff
click to change
<script type="text/javascript">
console.log('loaded');
var checkHash = function(){
if(location.hash==="#black"){
$('body').css("background-color","black");
}else if(location.hash==="#white"){
$('body').css("background-color","white");
}
}
//the event below will be trigger when you hit backbutton or the link
window.addEventListener("popstate", function(e) {
console.log('trigger when hit the back button')
checkHash();
});
</script>
</body>
</html>
IE9 FIX
If you need to implement the same behavior on IE9 you must listen the onhashchange, so you can trigger the code to change the background when backbutton was clicked.
<body onhashchange="alert('trigger the background change function')">

Create a dual function html Url Link?

Problem:
You have a regular set of URL links in a HTML page e.g.:
Foo Bar
You want to create a JavaScript function such that when any HTML links are clicked, instead of the client's browser navigating to that new URL "/foo/bar" a JavaScript function is executed instead (e.g. this may for example make an Ajaxian call and load the HTML data without the need to reload the page).
However if the JavaScript is disabled OR a spider crawls the site, the UTL links are maintained gracefully.
Is this possible? Does it already exist? What's the usual approach?
EDIT 1:
These are some great answers!
Just a follow on question:
If the user clicks on the back button OR forward button, this would naturally break (as in it would go back to the last physical page it was on as opposed to one that was loaded).
Is there any way (cross browser) to maintain the back/forward buttons?
(e.g create an array of links clicked and over ride the browser buttons and use the array to navigate)?
<script type="text/javascript">
function your_function() {
alert('clicked!');
}
</script>
<a onclick="your_function();" href="/foo/bar">Foo Bar</a>
If Javascript is off, the link behaves normally.
In this case, unless your_function() does not return false, the link will be followed when clicked as well.
To prevent this, either make your_function() return false, or add return false; just after the function call in your onclick attribute:
<script type="text/javascript">
function your_function() {
alert('clicked!');
return false;
}
</script>
<a onclick="your_function();" href="/foo/bar">Foo Bar</a>
Or:
<script type="text/javascript">
function your_function() {
alert('clicked!');
}
</script>
<a onclick="your_function(); return false;" href="/foo/bar">Foo Bar</a>
Using element.addEventListener()
With default anchor behaviour following click:
<script type="text/javascript">
document.addEventListener("load", function() {
document.getElementById("your_link").addEventListener("click", function() {
alert('clicked');
}, true);
}, true);
</script>
<a id="your_link" href="/foo/bar">Foo Bar</a>
Without:
<script type="text/javascript">
document.addEventListener("load", function() {
document.getElementById("your_link").addEventListener("click", function(event) {
event.preventDefault();
alert('clicked');
}, true);
}, false);
</script>
<a id="your_link" href="/foo/bar">Foo Bar</a>
Given current HTML and W3C APIs, I would go for:
<script src="linkify.js"> </script>
in the markup, with linkify.js containing something like:
window.onload= function() {
document.addEventListener('click', function(ev) {
ev.preventDefault();
var el = ev.target;
if (el.tagName === 'A') {
// do stuff with el.href
}
}, false);
};
See e.g. http://jsfiddle.net/alnitak/nrC7G/, or http://jsfiddle.net/alnitak/6necb/ for a version which doesn't use window.onload.
Note that this code uses a single listener function registered on the document object, which will act on every <A> tag on the page that doesn't trap clicks for itself.
Use an onclick attribute:
click?
The return false prevents the default behaviour, in the absence of JavaScript, however, the link will be followed.
function do_whatever (e)
{
e.preventDefault ();
// do whatever you want with e.target
}
var links = document.getElementsByTagName ("a");
for (var i=0; i<links.length; ++i)
links[i].addEventListener ('click', do_whatever);
http://jsfiddle.net/bTuN7/
All done inside script and it won't 'hurt' if JavaScript doesn't work.
If you think about AJAX, then you have to know, that googlebot tries to parse it. http://www.youtube.com/watch?v=9qGGBYd51Ts
You can code like:
$('a').click(function() {
doSomethingWithURL($(this).attr('href'));
return false;
});
JavaScript is not executed in case it's disabled or if it's some web crawler, so from my point of view this is preferable.
There's quite a few methods out there such as this:
http://www.malbecmedia.com/blog/development/coding-a-ajax-site-that-degrades-gracefully-with-jquery/
Remember, though, that by virtue of a well setup server and caching you're not going to gain yourself much performance with an Ajax Load.

Categories