I have a website with tabs, where each tab is in fact in the same table with an atribute that show it or not. Then a javascript function would change the attribute when you press on the tab.
The function is something like this:
function showHide(ID) {
switch (ID) {
case 'main':
document.getElementById('main').style.display = 'block';
document.getElementById('abstracts').style.display = 'none';
break;
case 'abstracts':
document.getElementById('main').style.display = 'none';
document.getElementById('abstracts').style.display = 'block';
break;
}
return true;
}
Then, the title of the tab is something like
Main
and the tab is
<tr id="main"> ... </tr>
The thing is that I would like to be able to have a URL for a tab, for example http://mypage.com#main or something like that, so when I enter to that URL, the tab main is focussed.
Is that possible?
At the bottom of your page or window.onload, read the hash and call your method.
(function(){
var hash = window.location.hash.substr(1);
showHide(hash);
}());
and if you want the url to change, you probably want to remove the return false.
You can use hashchange event listener here.
eg :window.addEventListener("hashchange", doThisWhenTheHashChanges, false);
Related
I'm quite new to javascript. I have a simple onbeforeunload function, which currently works for all the pages and I want it to activate for certain subpages (#clients, #products, #news) , but not for the first subpage of my domain (index.html). I'd like to avoid putting the script in each subpage, but rather would like to use conditional statement(s) to detect name of the subpage before the onbeforeunload function triggers. My current code below:
window.onbeforeunload = function(event) {
event.returnValue = "You have unsaved work";
};
I understand that I need to use window.location.href in some way, but haven't figured out yet. I tried to use the code below to get url or each site and then wanted to enter it into a case statement, the url is returned but the code from case doesn't work:
document.getElementById("demo").innerHTML =
"Page location is " + window.location.href;
Case code:
<script>
var text;
switch (window.location.href) {
case "http://mydomain/#/clients":
text = 1;
break;
case "http://mydomain/#/products/":
text = 2;
break;
case "http://mydomain/#/news":
text = 3;
break;
default
text = 4;
break;
}
document.getElementById("demo").innerHTML = "Number is " + text;
</script>
Thank you
"window.location.href" returns the entire URL, use location.pathname instead. Also, make sure to add the path names (including extension) to the pathsToAddTheScript Array.
Try this.
var pathsToAddTheScript = ['clients', 'products'];
if(window.location.pathname in pathsToAddTheScript) {
window.onbeforeunload = function(event) {
event.returnValue = "You have unsaved work";
};
}
I have a user script that does some stuff after clicking a button. By clicking the same button again (like a toggle button), I want it to 'revert' back to default. By default I mean the on page load content. Check my code:
var myTbl = document.getElementsByClassName("myTable")[0];
var myCells = myTbl.getElementsByTagName("td");
myCells[2].innerHTML = "<span id='myButton' class='button'>Do something / Revert</span>";
document.getElementById("myButton").addEventListener("click", doSomething, false);
function doSomething() {
// do some stuff with myTbl
document.getElementById("myButton").removeEventListener("click", doSomething, false);
document.getElementById("myButton").addEventListener("click", revertToDefault, false);
}
function revertToDefault() {
// location.reaload();
}
I could do it with location.reaload();, but that's not what I want. I would prefer to save the default on load content in a variable like I did with the variable myTbl var myTbl = document.getElementsByClassName("myTable")[0]; and preserve that default content and then simply save that default content in the variable myTbl myTbl = defaultTbl; when executing the revertToDefault() function. What's the correct code to do that? Is there a better way of doing that, perhaps without the need of saving everything in a variable?
A possible working solution:
var myTbl = document.getElementsByClassName("myTable")[0];
var defaultTbl = myTbl.innerHTML; // this way defaultTbl remains intact while manipulating myTbl object
function revertToDefault() {
myTbl.innerHTML = defaultTbl;
}
I have a button on my website, which plays the music when you click on it and in the same time it changes the text inside of the button (to "Go to SoundCloud".)
I want that button (with the new text on it) to redirect to SoundCloud when I click on it.
Now I got both when click first time, which is redirect to SoundCloud and play the track. (plus it changes the text)
Any ideas, how to solve this problem? Thx!
var links = document.getElementById("playButton");
links.onclick = function() {
var html='<iframe width="100%" height="450" src="sourceOfMyMusic"></iframe>';
document.getElementById("soundCloud").innerHTML = html;
var newTexts = ["Go to SoundCloud"];
document.getElementById("playButton").innerHTML = newTexts;
newTexts.onclick = window.open('http://soundcloud.com/example');
};
Use a variable that indicates whether it's the first or second click.
var first_click = true;
links.onclick = function() {
if (first_click) {
// do stuff for first click
first_click = false;
} else {
// do stuff for second click
}
}
Just redefine the onclick after the first function call.
Put the onclick on the button instead of the html.
document.getElementById("playButton").onclick=window.open('http://soundcloud.com/example');
Another option in some cases is to use a ternary operator and a boolean toggle expression:
let btn = document.querySelector('.button');
let isToggledOn = false;
btn.addEventListener ('click', function(e) {
e.target.textContent = !isToggledOn ? 'Is ON' : 'Is OFF';
isToggledOn = !isToggledOn;
});
newTexts.onclick is not creating a function to open a window, it is simply taking the return value of window.open which is being executed right away.
It should look like:
newTexts.onclick = () => window.open('http://soundcloud.com/example');
Also this will not work as intended because newTexts is not the actual DOM element, you need to attach the new onclick on the element and not the array...
But to other answers in this page, the logic is hard to read, so I'd advise to refactor the logic to be more readable.
Rewriting the question -
I am trying to make a page on which if user leave the page (either to other link/website or closing window/tab) I want to show the onbeforeunload handeler saying we have a great offer for you? and if user choose to leave the page it should do the normal propogation but if he choose to stay on the page I need him to redirect it to offer page redirection is important, no compromise. For testing lets redirect to google.com
I made a program as follows -
var stayonthis = true;
var a;
function load() {
window.onbeforeunload = function(e) {
if(stayonthis){
a = setTimeout('window.location.href="http://google.com";',100);
stayonthis = false;
return "Do you really want to leave now?";
}
else {
clearTimeout(a);
}
};
window.onunload = function(e) {
clearTimeout(a);
};
}
window.onload = load;
but the problem is that if he click on the link to yahoo.com and choose to leave the page he is not going to yahoo but to google instead :(
Help Me !! Thanks in Advance
here is the fiddle code
here how you can test because onbeforeunload does not work on iframe well
This solution works in all cases, using back browser button, setting new url in address bar or use links.
What i have found is that triggering onbeforeunload handler doesn't show the dialog attached to onbeforeunload handler.
In this case (when triggering is needed), use a confirm box to show the user message. This workaround is tested in chrome/firefox and IE (7 to 10)
http://jsfiddle.net/W3vUB/4/show
http://jsfiddle.net/W3vUB/4/
EDIT: set DEMO on codepen, apparently jsFiddle doesn't like this snippet(?!)
BTW, using bing.com due to google not allowing no more content being displayed inside iframe.
http://codepen.io/anon/pen/dYKKbZ
var a, b = false,
c = "http://bing.com";
function triggerEvent(el, type) {
if ((el[type] || false) && typeof el[type] == 'function') {
el[type](el);
}
}
$(function () {
$('a:not([href^=#])').on('click', function (e) {
e.preventDefault();
if (confirm("Do you really want to leave now?")) c = this.href;
triggerEvent(window, 'onbeforeunload');
});
});
window.onbeforeunload = function (e) {
if (b) return;
a = setTimeout(function () {
b = true;
window.location.href = c;
c = "http://bing.com";
console.log(c);
}, 500);
return "Do you really want to leave now?";
}
window.onunload = function () {
clearTimeout(a);
}
It's better to Check it local.
Check out the comments and try this: LIVE DEMO
var linkClick=false;
document.onclick = function(e)
{
linkClick = true;
var elemntTagName = e.target.tagName;
if(elemntTagName=='A')
{
e.target.getAttribute("href");
if(!confirm('Are your sure you want to leave?'))
{
window.location.href = "http://google.com";
console.log("http://google.com");
}
else
{
window.location.href = e.target.getAttribute("href");
console.log(e.target.getAttribute("href"));
}
return false;
}
}
function OnBeforeUnLoad ()
{
return "Are you sure?";
linkClick=false;
window.location.href = "http://google.com";
console.log("http://google.com");
}
And change your html code to this:
<body onbeforeunload="if(linkClick == false) {return OnBeforeUnLoad()}">
try it
</body>
After playing a while with this problem I did the following. It seems to work but it's not very reliable. The biggest issue is that the timed out function needs to bridge a large enough timespan for the browser to make a connection to the url in the link's href attribute.
jsfiddle to demonstrate. I used bing.com instead of google.com because of X-Frame-Options: SAMEORIGIN
var F = function(){}; // empty function
var offerUrl = 'http://bing.com';
var url;
var handler = function(e) {
timeout = setTimeout(function () {
console.log('location.assign');
location.assign(offerUrl);
/*
* This value makes or breaks it.
* You need enough time so the browser can make the connection to
* the clicked links href else it will still redirect to the offer url.
*/
}, 1400);
// important!
window.onbeforeunload = F;
console.info('handler');
return 'Do you wan\'t to leave now?';
};
window.onbeforeunload = handler;
Try the following, (adds a global function that checks the state all the time though).
var redirected=false;
$(window).bind('beforeunload', function(e){
if(redirected)
return;
var orgLoc=window.location.href;
$(window).bind('focus.unloadev',function(e){
if(redirected==true)
return;
$(window).unbind('focus.unloadev');
window.setTimeout(function(){
if(window.location.href!=orgLoc)
return;
console.log('redirect...');
window.location.replace('http://google.com');
},6000);
redirected=true;
});
console.log('before2');
return "okdoky2";
});
$(window).unload(function(e){console.log('unloading...');redirected=true;});
<script>
function endSession() {
// Browser or Broswer tab is closed
// Write code here
alert('Browser or Broswer tab closed');
}
</script>
<body onpagehide="endSession();">
I think you're confused about the progress of events, on before unload the page is still interacting, the return method is like a shortcut for return "confirm()", the return of the confirm however cannot be handled at all, so you can not really investigate the response of the user and decide upon it which way to go, the response is going to be immediately carried out as "yes" leave page, or "no" don't leave page...
Notice that you have already changed the source of the url to Google before you prompt user, this action, cannot be undone... unless maybe, you can setimeout to something like 5 seconds (but then if the user isn't quick enough it won't pick up his answer)
Edit: I've just made it a 5000 time lapse and it always goes to Yahoo! Never picks up the google change at all.
I have a call to an onclick that is already created before.
The button already has an onclick, but I need to add one more parameter before it does the submit.
Here's the View Source Code on the button:
<td valign='top' align='right' >
<button name="Complete" title="Complete"
onClick="document.forms.Maker.action='http://example.com:8080/internal/Step.jsp?theId=19032&target=step20&type=Full';
document.forms.Maker.submit();return false;">Complete</button>
</td>
This is a modification I made to add a confirmation after the user presses the button, and I also added so it shows what the onclick currently has:
function addEventConfirmation(element, type){
var old = element['on' + type] || function() {};
element['on' + type] = function () {
if (confirm("Are you sure?")){
old.call(this);
alert(old);
} else { return false; }
};
}
This is the alert from the before code:
function onclick()
{
document.forms.Maker.action='http://example.com:8080/internal/Step.jsp?theId=19032&
target=step20&type=Full';document.forms.Maker.submit();return false;
}
The result should show something like this:
function onclick()
{
document.forms.Maker.action='http://example.com:8080/internal/Step.jsp?theId=19032&
target=step20&type=Full&newParam=true';document.forms.Maker.submit();return false;
}
Try this: make the action value a variable.
var oldURI = "http://mysite.com:8080..."
var href = "oldURI" + "&newParam=true"
document.forms.Maker.action='href'
If this Html is your own code, do just like this :
document.getElementById('Complete').onclick = function()
{
document.forms.Maker.action=
'http://mysite.com:8080/internal/Step.jsp?theId=19032&
target=step20&type=Full&newParam=true';
document.forms.Maker.submit();
return false;
}
else if you are trying to change this event handler from others website do this :
put website in an iframe named 'myframe' and code like this :
document.getElementById('Complete').onclick = function()
{
document.forms.Maker.action=
'http://mysite.com:8080/internal/Step.jsp?theId=19032&
target=step20&type=Full&newParam=true';
document.forms.Maker.submit();
return false;
}
but remember to turn cross-domain data source access restriction of your browser off !!!
for example in ie :
Internet Options -> Security -> Custom Settings (Internet Zone) ->
Enable Access data sources across domains