Jquery hashchange problems in firefox - javascript

I am having a problem with the hashchange event in Firefox. We are using the JQuery hashchange plugin provided by Ben Alman. The code is as follows.
$(window).hashchange(function (e) {
alert("Hello");
//we want to perform a post in here.
});
var temp = "#123";
if (temp !== "") {
if (window.location.hash == temp) {
$(window).hashchange();
}
else{
window.location.hash = temp;
}
}
else {
window.location.hash = "#Home/Home";
};
Now this works fine in IE9 and Chrome, however in Firefox, I see the alert, but as soon as I click OK, the page refreshes, displays the alert again, and continues infinitely. Is there some sort of weird behaviour that Firefox uses that I am unaware of? Or is there simply some other problem that is hidden deeper?

In some browsers window.location.hash includes the # and in some don't so its better if your ignore it while comparing the hash value in your code.
Try this.
$(window).hashchange(function (e) {
alert("Hello");
//we want to perform a post in here.
});
//Remove hash from here which will be compared with window.location.hash
var temp = "123";
if (temp !== "") {
//Replace # by empty nothing
if (window.location.hash.replace('#', '') == temp) {
$(window).hashchange();
}
else{
window.location.hash = '#' + temp;//Now add the hash here
}
}
else {
window.location.hash = "#Home/Home";
};

We located the problem as occuring in MicrosoftAjax.js and found the following solution:
Firefox 6 Infinite Page Refresh With Page With Hash Tags

Related

How to disable the browser back button using javascript in a HTML page. Can we get any callback method trigerred on click of backbutton on browser

How to disable the browser back button using javascript in a HTML page. Can we get any callback method trigerred on click of backbutton on browser using Javascript and not using Jquery Mobile library.
Solution would be really appreciated. I tried with few solutions online, but nothing seemed to work.
You should never do that. https://www.irt.org/script/311.htm
By the way, you may just warn the user using window.onbeforeunload.
You can-not actually disable browser back button. And there is no event for capturing the back button click.
If it is really necessary you can do something like that:
(function (global) {
var _extra_hash = "!";
var noBack = function () {
global.location.href += "#";
global.setTimeout(function () {
global.location.href += _extra_hash;
}, 50);
};
global.onhashchange = function () {
if (global.location.hash !== _extra_hash) {
global.location.hash = _extra_hash;
}
};
global.onload = function () {
noBack();
// this is for disabling backspace on page except on input fields and textarea..
/*document.body.onkeydown = function (e) {
var elm = e.target.nodeName.toLowerCase();
if (e.which === 8 && (elm !== 'input' && elm !== 'textarea')) {
e.preventDefault();
}
// stopping event bubbling up the DOM tree..
e.stopPropagation();
};*/
}
})(window);
But the user can still kill the tab. Anyway, It is generally a bad idea overriding the default behavior of web browser.

External Link Notification - JavaScript or JQuery

I am looking for a way to set it up so that when an external link is clicked it will warn people that they are leaving the site. Preferably, it would darken the screen and display a message in the middle of the screen in a box with the option to click OK or Cancel.
I tried to use this code:
$("a.external").click(function () {
alert("You are about to proceed to an external website. The Great Western Market has no control over the content of this site. Click OK to proceed.");
});
and give each link a class of external but it doesn't seem to work. I don't want to use this because it means that the client will have to remember to add the class I would prefer something more automatic.
I also tried to use this code to do so but to no avail:
$('a').filter(function() {
return this.hostname && this.hostname !== location.hostname;
})
.click(function () {
var x=window.confirm('You are about to proceed to an external website. The Great Western Market has no control over the content of this site. Click OK to proceed.');
var val = false;
if (x)
val = true;
else
val = false;
return val;
});
I am using WordPress 3.8.1.
Thanks in advance for any help you can give.
Your filter logic should be correct, Try using the confirm function, and using jQuery instead of $.
jQuery('a').filter(function() {
return this.hostname && this.hostname !== location.hostname;
}).click(function(e) {
if(!confirm("You are about to proceed to an external website."))
{
// if user clicks 'no' then dont proceed to link.
e.preventDefault();
};
});
I tried this out in dev tools on your site and it seems to work correctly if you use jQuery. I think you may have some plugin that is causing conflicts with $.
JSFiddle Demo
Try using confirm instead of alert since that will pause and wait for user input. You'll then need function(e){ e.preventDefault(); } to prevent the default link actions.
To identify just external links you might do something like this:
var ignoreClick = false;
$(document).ready( function(){
$('input[type="submit"], input[type="image"], input[type="button"], button').click(function(e) {
ignoreClick = true;
});
$(document).click(function(e) {
if($(e.target).is('a'))
checkLink(e);
});
$('a').click(function(e) {
checkLink(e);
return true;
});
checkLink = function(e){
// bubble click up to anchor tag
tempTarget = e.target;
while (!$(tempTarget).is('a') && !!tempTarget.parentElement) {
tempTarget = tempTarget.parentElement;
}
if ($(tempTarget).is('a')){
if(!!tempTarget && $(tempTarget).is('a') &&
(tempTarget.hostname == "" || tempTarget.hostname == "#" || tempTarget.hostname == location.hostname)){
ignoreClick = true;
}
}
}
});
and to catch people with a message you might use beforeunload and the confirm option
$(window).bind("beforeunload", function (e) {
if (!ignoreClick){
if(!confirm("Leaving website message")) {
e.preventDefault();
}
}
});
It worked pretty well to me. I just removed unnecesary variables, but original script worked fine.
$('a').filter(function() {
return this.hostname && this.hostname !== location.hostname;
})
.click(function () {
return window.confirm('You are about to proceed to an external website. The Great Western Market has no control over the content of this site. Click OK to proceed.');
});
http://jsfiddle.net/3dkAN/1/
EDIT
Following #user1308743's line, seems that in cgmp.framework.min.js is summoning the jQuery.noConflict() mode, that unbinds the $() function for jQuery. So please use jQuery() for any jQuery implementation

detect back button click in browser [duplicate]

This question already has answers here:
Intercepting call to the back button in my AJAX application
(12 answers)
Closed 8 years ago.
I have to detect if a user has clicked back button or not.
For this I am using
window.onbeforeunload = function (e) {
}
It works if a user clicks back button. But this event is also fired if a user click F5
or reload button of browser. How do I fix this?
So as far as AJAX is concerned...
Pressing back while using most web-apps that use AJAX to navigate specific parts of a page is a HUGE issue. I don't accept that 'having to disable the button means you're doing something wrong' and in fact developers in different facets have long run into this problem. Here's my solution:
window.onload = function () {
if (typeof history.pushState === "function") {
history.pushState("jibberish", null, null);
window.onpopstate = function () {
history.pushState('newjibberish', null, null);
// Handle the back (or forward) buttons here
// Will NOT handle refresh, use onbeforeunload for this.
};
}
else {
var ignoreHashChange = true;
window.onhashchange = function () {
if (!ignoreHashChange) {
ignoreHashChange = true;
window.location.hash = Math.random();
// Detect and redirect change here
// Works in older FF and IE9
// * it does mess with your hash symbol (anchor?) pound sign
// delimiter on the end of the URL
}
else {
ignoreHashChange = false;
}
};
}
}
As far as Ive been able to tell this works across chrome, firefox, haven't tested IE yet.
Please try this (if the browser does not support "onbeforeunload"):
jQuery(document).ready(function($) {
if (window.history && window.history.pushState) {
$(window).on('popstate', function() {
var hashLocation = location.hash;
var hashSplit = hashLocation.split("#!/");
var hashName = hashSplit[1];
if (hashName !== '') {
var hash = window.location.hash;
if (hash === '') {
alert('Back button was pressed.');
}
}
});
window.history.pushState('forward', null, './#forward');
}
});
best way I know
window.onbeforeunload = function (e) {
var e = e || window.event;
var msg = "Do you really want to leave this page?"
// For IE and Firefox
if (e) {
e.returnValue = msg;
}
// For Safari / chrome
return msg;
};
I'm detecting the back button by this way:
window.onload = function () {
if (typeof history.pushState === "function") {
history.pushState("jibberish", null, null);
window.onpopstate = function () {
history.pushState('newjibberish', null, null);
// Handle the back (or forward) buttons here
// Will NOT handle refresh, use onbeforeunload for this.
};
}
It works but I have to create a cookie in Chrome to detect that i'm in the page on first time because when i enter in the page without control by cookie, the browser do the back action without click in any back button.
if (typeof history.pushState === "function"){
history.pushState("jibberish", null, null);
window.onpopstate = function () {
if ( ((x=usera.indexOf("Chrome"))!=-1) && readCookie('cookieChrome')==null )
{
addCookie('cookieChrome',1, 1440);
}
else
{
history.pushState('newjibberish', null, null);
}
};
}
AND VERY IMPORTANT, history.pushState("jibberish", null, null); duplicates the browser history.
Some one knows who can i fix it?
Since the back button is a function of the browser, it can be difficult to change the default functionality. There are some work arounds though. Take a look at this article:
http://www.irt.org/script/311.htm
Typically, the need to disable the back button is a good indicator of a programming issue/flaw. I would look for an alternative method like setting a session variable or a cookie that stores whether the form has already been submitted.
I'm assuming that you're trying to deal with Ajax navigation and not trying to prevent your users from using the back button, which violates just about every tenet of UI development ever.
Here's some possible solutions:
JQuery History
Salajax
A Better Ajax Back Button

how to open outside links in a new tab

On my website i have many outside links, as well as internal links.
i'd like some kind of solution in javascript or w/e that detects outside links and opens them in a new tab, but leaves internal links to be opened in the same tab.
thanks! =)
function getXterlinks()
{
var Xterlinks = document.getElementsByTagName('A');
for (var i=0;i<Xterlinks.length;i++)
{
var eachLink = Xterlinks[i];
var regexp_isYourdomain="your-domain.com";
var regexp_ishttp=/(http(.)*:\/\/)/;
if( (eachLink.href != null) && (eachLink.href.match(regexp_isYourdomain) == null) && eachLink.href.match(regexp_ishttp)!=null )
{
eachLink.target ="_blank";
}
}
}
Source: http://www.mediawiki.org/wiki/Manual:Opening_external_links_in_a_new_window#How_to_make_external_links_open_in_a_new_window
Yeah, well, jQuery's still JavaScript. How about:
$('a[href^="http://your-domain.com"]').attr("target", "_self");
$('a').not('a[href^="http://your-domain.com"]').attr("target", "_blank");
Not sure about the second, though, but you get the idea.
I wrote this solution for my personal web site. As long as you like jQuery (which you should, imho), you can include this in a common js file and forget about it. It will work with dynamic content, and will not force internal links to open in the current tab if you set target="_blank".
$(function() {
$('body').on('click', 'a', function() {
var currentHost = document.location.protocol+'//'+document.location.hostname;
if (this.href.indexOf(currentHost) != 0 && (this.href.indexOf('http') == 0 || this.href.indexOf('ftp') == 0)) {
window.open(this.href, '_blank');
return false;
}
});
});
Note: If you are using jQuery < 7, use .bind() instead of .on()
See it in action on http://www.seanknutson.com.

Jquery href with hash

i am using tis code for tab navigation.
function hashIt(toHash) {
toHash == ""
? window.location.hash = window.location.hash.replace( /#.*/, "")
: window.location.hash = toHash;
return false;
}
and also i am using jquery popup on page onload. a hyperlink in the popup is not working,
if i remove the hashIt function its fine.
but i want both. Please help me out.
Ramesh.
Your function should just be
function hashIt(toHash) {
window.location.hash = toHash;
}
without all the extra logic. Then to clear the hash, just call hashIt("");
try to remove return false;, then check if it still works... (suspecting something)

Categories