Understanding HTML anchor tag - javascript

Let'u start with following example:
Create three pages in same directory:
test.html
index.html
Your test.html:
<html>
<head>
<script>
function test()
{
alert('Going to google.com?');
window.location="http://google.com";
}
</script>
</head>
<body>
google.com<br/>
<input type="button" value="google" onclick="test();" />
google.com<br/>
</body>
</html>
Now check test.html page on IE as well as firefox or crome.
You will notice following points:
Button works perfectly.
First hyperlink works differently in IE and other browser. In IE, it brings us back to index.html page, while in firefox, it stays on same page.
For first hyperlink, window.location fails.
Second hyperlink you cannot click on that, as mouse over event will fire first, and it works perfectly!
Why?
My major interest is on 3rd point, as it even gives us alert, window.location fails.

The JavaScript event fires, window.location is set, then the default action of the link fires and the browser goes to '', which (IIRC) resolves as the current URI.
This is the same effect you get if you click on a link, then quickly click on a different link. The browser doesn't have time to go to the first one before receiving the instruction to go to the second one, and it goes to the second one. If you delay the return of the function (by putting the alert second) it gives enough time for the request for the first URL to go through for that one to be visited instead of the second.
You would need to cancel the default action which, when you're using intrinsic event attributes (not recommended, unobtrusive JavaScript is the way forward), is done by returning false.
onclick="test(); return false;"

Try this:
<html>
<head>
<script>
function test()
{
alert('Going to google.com?');
window.location="http://google.com";
return false;
}
</script>
</head>
<body>
google.com<br/>
<input type="button" value="google" onclick="Javascript:return test();" />
google.com<br/>
</body>
</html>

Related

Can't see localstorage event across tabs

I'm trying to create a simple proof-of-concept regarding the use of localStorage to trigger tabs in my application when changes occur. I know this is possible based on other articles I've seen. I understand the spec states the event will fire on ever page except the one I'm on - this is in fact what I want. However, I can't seem to get this simple demo to actually work.
I've taken the code below, and opened up multiple tabs of it. Using my Chrome Dev Tools, I can check >localStorage in the console and see the value before and after the "Add" and "Clear" buttons are pressed - they are in fact functioning as desired in storing and clearing the key value pair into local storage, yet the event isn't firing the alert.
I even placed breakpoints in the javascript in my Chrome Dev Tools of each tab, yet I can never seem to get the "onStorageEvent" function to hit in any tab opened.
What am I doing wrong?
<!DOCTYPE html>
<html>
<head>
<title>Tab1</title>
</head>
<body>
<button id="add" onclick="localStorage.setItem('tab','changed')">Add</button>
<button id="clear" onclick="localStorage.clear()">Clear</button>
<script type="text/javascript">
function onStorageEvent() {
alert("storage event: " + localStorage.getItem("tab"));
}
window.addEventListener('storage', onStorageEvent, false);
</script>
</body>
</html>
In order for the window.addEventListener to work on storage:
you MUST access the page using web-server (http://a.b.c.d/ or http://domain)
Direct access (using file:/// or c:\file.html will not work.
(chrome and ie ignore it, firefox and safari can run it anyway).
I would consider also removing the 3rd, it is not relevant to elements in your DOM tree, and it might cause troubles (let the browser have it's defaults).
This code was tested in Chrome 52, Firefox 47+48, IE 11, Safari 5.7.1
<!DOCTYPE html>
<html>
<head>
<title>Tab1</title>
</head>
<body>
<button id="add" onclick="localStorage.setItem('tab','changed')">Add</button>
<button id="clear" onclick="localStorage.clear()">Clear</button>
<script type="text/javascript">
function onStorageEvent() {
alert("storage event: " + localStorage.getItem("tab"));
}
window.addEventListener('storage', onStorageEvent);
</script>
</body>
</html>

javascript print() method is not working as expected

I have a simple HTML code to print the page. Below is the code:
<!DOCTYPE html>
<html>
<head>
<script>
function printPage()
{
var w = window.open("http://www.sigmaaldrich.com/catalog/CofADocRequest.do?symbol=209104&LotNo=MKBP0842V&brandTest=SIGMA","_self");
window.focus();
window.print();
}
</script>
</head>
<body >
<input type="button" onclick="printPage()" value="print a div!" />
</body>
</html>
What the code does is, it displays a button, on clicking that button it calls a function. The function uses open() to open a new URL in the same page by using the “_self ” parameter.
As we can see in the code, the print() is being called after the call to open method. But in my browser IE11, the print pop is being shown befor loading the page.
Due to this I am not printing the correct page.
Can anybody help me on this.
The problem is that window refers to the current window, which is the original.
By opening a new window in self you replace the page, this is basically a redirect.
And if you open it via popup and print it as w.print() than you run into cross-origin security error.
You could use iframe to this with a proxy as shown here
How do print specific content inside the iframe
and
here
How do print specific content inside the iframe

Chrome JavaScript console is null after submitting the page

This was unexpected. I use Chrome as my primary development browser and make generous use of "console.log" (way better than alerts!)
Anyway, I have a page inside an IFrame (for uploading images). That page includes scripts that often write out to the console window (console.log) for tracking purposes. The first time the parent page submits the embedded page via script, everything goes smoothly. If I, however, then attempt to submit the page a second time I get the error ...
Uncaught TypeError: Cannot call method 'log' of null
All of a sudden it seems that the console is no longer available. If I replace it with an alert the alert box appears as expected, but the page no longer submits either.
Has anybody experienced anything like this before?
I want to thank folks for their responses. I did not include any code in the OP because it is an extensive script and parsing out an "example" of what I was attempting to do so that it wasn't too tedious to go through would likely strip out any relevancy.
I am posting, however to say that I did discover the problem.
I have PageA which contains an IFrame which is in turn loaded with PageB.
<html>
<head><title>PageA</title></head>
<body>
<IFrame src="PageB" name="frame1" id="frame1"></IFrame>
</body>
</html>
PageB contains a function that needs to be called from PageA when a button is clicked.
<!-- PageB -->
<html>
<head><title>PageB</title></head>
<body>
<form id="form1" name="form1" >
</form>
<script>
var SubmitForm = function(){
var $form = $("form[id$='form1']");
$form[0].submit(); // this was not firing
console.log("some log output"); // this was throwing an error
};
</script>
</body>
</html>
<!-- PageA -->
<html>
<head><title>PageA</title></head>
<body>
<IFrame src="PageB" name="frame1" id="frame1"></IFrame>
<button onclick="submitIFrameForm()">Submit</button>
<script>
var frameWindow = frames["frame1"];
var frameForm = frameWindow.SubmitForm;
function submitIFrameForm(){
frameForm();
};
</script>
</body>
</html>
THE PROBLEM
When PageA first loads, the IFrame is loaded with PageB and the script in PageA makes it's reference (frameForm) to the "SubmItForm()" function on PageB. When I click on the submit form button in PageA, PageB is submitted back to the server. No problem ...
However when PageB is submited it is UNLOADED from the window. So when I click on the
submit button in PageA a second time, although PageB may reload it is a different instance of the page. Therefore all the variables which reference the original PageB are now pointing to nothing ... hence the window that console was referencing no longer exists, so the "log" method cannot run.
THE FIX
Instead of creating a global reference to the contents of the IFrame, we must re-establish this reference to the function each time the button is clicked. (Since the IFrame is a member of PageA we do not need to re-establish the IFrame reference).
<!-- PageA -->
<html>
<head><title>PageA</title></head>
<body>
<IFrame src="PageB" name="frame1" id="frame1"></IFrame>
<button onclick="submitIFrameForm()">Submit</button>
<script>
var frameWindow = frames["frame1"];
function submitIFrameForm(){
frameWindow.SubmitForm(); // move the reference to the click event handler
};
</script>
</body>
</html>
I hope that this made sense and that it helps someone out there. I get caught up on this kind of stuff constantly.

Uncaught TypeError: Cannot read property 'fancybox' of undefined - Google Chrome only error?

I'm using fancybox to display an iframe and close it upon clicking a button. This is only for testing purposes. The closing function works on IE and FF but not on Chrome.
<title>Test</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
<script type="text/javascript" src="fancybox/jquery.fancybox-1.3.4.pack.js"></script>
<link rel="stylesheet" href="fancybox/jquery.fancybox-1.3.4.css" type="text/css" media="screen" />
<link rel="stylesheet" type="text/css" href="default.css" />
<link rel="stylesheet" type="text/css" href="default2.css" />
</head>
<body id="editadd">
<h1>Create</h1>
<div class="centered">
<fieldset>
<legend>Details</legend>
<p>Name: <input type="text" /></p>
</fieldset>
<fieldset>
<legend>Add Assignments</legend>
<p>stuff</p>
<input type="text" value="stuff" />
<br />
</fieldset>
<br />
<input type="submit" OnClick="parent.$.fancybox.close();" value="Save"/>
<input type="submit" OnClick="parent.$.fancybox.close();" value="Cancel"/>
</div>
</body>
Upon clicking the Save or Cancel button nothing happens (it closes on FF and IE and returns focus to the previous page). I looked at the Javascript console on Chrome to see what was happening and the error is:
Uncaught TypeError: Cannot read property 'fancybox' of undefined
(anonymous function)
onclick
I've also tried "javascript:window.parent.$.fancybox.close();" instead. I can't ask in google groups (where fancybox's forum is located) because for some reason it's blocked on campus.
You're having trouble with the Same origin policy: The framed page is served at a different host than the parent window. My answer consists of two solutions:
Attaching and handling an onload event at the <iframe>, http://jsfiddle.net/BYssk/1/
Using window.postMessage (see bottom of answer, recommended), http://jsfiddle.net/5fGRj/1/
To deal with this, you've can use one of the following methods. Both methods requires that the page in the frame reloads when it has to be closed. This can be achieved by submitting the form. No onclick handlers are necessary. Preview of both methods: http://jsfiddle.net/BYssk/1/
1. If your iFrame is embedded in the page:
<script>
var fancyboxClose = (function(){ //Define a function
var loaded = 0; //Define a local, "PRIVATE" counter
return function(){ //Define a public method
// Increases the counter by one, modulo 2:
// Every "first" time, the "loaded++" returns an even number -> false
// When the page reloads again, the fancybox is submitted. The counter
// increases again -> odd number => modulo 2 = 1 => true
if(loaded++ % 2) $.fancybox.close();
}
})();
</script>
<iframe src=".." onload="fancyboxClose()"></iframe>
2. If your iFrame is dynamically created:
//The code below is executed inside some function. Definitely NOT globally
var loaded = 0;
$("<iframe>") // Create frame
.load(function(){ // Bind onload event
if(loaded++ % 2) $.fancybox.close();
})
.attr("src", "...") // Set src attribute
.appendTo("body"); // Append the iframe, anywhere. For example: <body>
The engine behind this method:
When the frame's content is loaded, an onload event is triggered (1).
When the user submits the form, or exits the page inside the frame, another onload event is triggered (2).
The script doesn't do anything at the first onload event. At the second onload event however, the script calls the $.fancybox.close() method.
Alternative method
Another method consists of using the modern window.postMessage method. It's much more reliable than the previous method, and supported in all modern browsers. Fiddle: http://jsfiddle.net/5fGRj/1/
Script in main window:
function closeFancyBox(){
$.fancybox.close();
}
window.addEventListener("message", closeFancyBox, false);
Necessary code inside the framed page:
<script>
function initiateClose(){
parent.postMessage("Close fancybox please.", "*");
// * should be more specific, for security reasons
// See https://developer.mozilla.org/en/DOM/window.postMessage
}
</script>
PostMessage method<br />
<input type="submit" value="Inititate 'close'" onclick="initiateClose()">
The problem is jquery 1.9.1 and old fancybox. either use fancybox 1.3.xx with jquery 1.8.x
or just update the latest version of fancybox 2.1.x http://www.fancyapps.com/fancybox/#license
If you are logged in to WordPress on a specific host as I was where fancybox was loading from, logging out or viewing the resource in an incognito window or tab did not produce the error in the Chrome Developer Tools Console panel while checking it as it did while logged in.

javascript rendered HTML page still loading

I have a mother page, where is jvscrpt function called openWin() , which opens a new window.
Here is my code:
<html>
<head>
<script type="text/javascript">
function openWin()
{
win=window.open();
win.document.write("<html>");
win.document.write("<head>");
win.document.write("<style type=\"text/css\">");
win.document.write("#media print{.input {display:none}}");
win.document.write("</style>");
win.document.write("</head>");
win.document.write("<body>");
win.document.write("<table align=\"center\">");
win.document.write("<tr><td>result:</td><td>100,--€</td></tr>");
win.document.write("<tr><td colspan=\"2\" id=\"idcko\"><input type=\"button\" value=\"click\" class=\"input\" onclick=\"window.print();\"/></td></tr>");
win.document.write("</table>");
win.document.write("</body>");
win.document.write("</html>");
}
</script>
</head>
<body>
<form>
<input type="button" value="Click me!" onclick="openWin();" />
</form>
</body>
</html>
When I click on button "Click me!" a new window appears, but browser can`t stop loading the page.The page has full functionality,but for example when I want to see source code in Mozilla, I get only a blank page.
Please help...
call
win.document.close();
At the end(after the last write() )
It signals to the browser that the write-process is finished and the document is complete.
but for example when I want to see
source code in Mozilla, I get only a
blank page.
This is because the source was written by your javascript - this is the same as AJAX (you can't view the changes in the source).
Perhaps you would be better of just opening a new page and pass whatever paramters it needs either via a GET/POST or server-side.

Categories

Resources