Why do I need 'javascript:' in the call to my javascript function? - javascript

Newer to javascript and trying to learn why this works, searching Google has led to no answers (although I maybe searching using the incorrect terms).
I'm am making a call to a function during an onclick event within an <a></a>. I was able to get the function finally working (with a suggestion from a coworker) by adding in 'javascript:' before making the function. Without the javascript: portion in the onclick, my function was not being called upon.
It now works but I don't understand what that is doing, the other programmer who suggested putting it in the call also isn't sure what exactly it does.
Here is a simplified version of the code used:
#1 .jspf higher up which includes page #2 to display it's contents
function createTagging(1, 2) {
cmCreateElementTag(1 + ", " + 2,"TagName");
}
HTML in .jspf file #2 further down website makes the call to function in file #1
<a id="CatEntry" href="https://aurl"
onclick="javascript: createTagging('parameter1', 'parameter2');"
title="atitle" aria-label="alabel">
<img id="ThumbNailImage_59244" src="https://image.jpg"
alt="" border="0"/>
</a>
-Troy

Why do I need 'javascript:' in the call to my javascript function?
You don't. It's an onclick handler. You use the javascript: pseudo-protocol where a URL is expected (for instance, if you'd used href instead of onclick). onclick expects JavaScript code.
In fact, it only works because JavaScript has labelled statements, and javascript: is a valid label. It's completely ignored.
Without the javascript: portion in the onclick, my function was not being called upon.
With respect, that must have been observational error. Again, in an onclick handler, it makes no difference whether you have javascript: in front of it or not. If it wasn't working, and then it was working, you changed something else at the same time you added javascript:.

onclick attribute is always calling javascript in HTML.
onclick="createTagging('parameter1', 'parameter2');"
It is only necessary if you use not an event, but href. There you need to add the protocoll as well for Javascript.

Related

how to call a onclick function in <a> tag?

I want to open a new window on click of 1
$leadID = "<a href='javascript:onclick=window.open(lead_data.php?leadid=1, myWin, scrollbars=yes, width=400, height=650);'>1</a>";
It is not showing me error. Is there any other way to open new window?
Here is the fiddle
http://jsfiddle.net/ankurdhanuka/uwypv/
Try onclick function separately it can give you access to execute your function which can be used to open up a new window, for this purpose you first need to create a javascript function there you can define it and in your anchor tag you just need to call your function.
Example:
function newwin() {
myWindow=window.open('lead_data.php?leadid=1','myWin','width=400,height=650')
}
See how to call it from your anchor tag
<a onclick='newwin()'>Anchor</a>
Update
Visit this jsbin
http://jsbin.com/icUTUjI/1/edit
May be this will help you a lot to understand your problem.
Fun! There are a few things to tease out here:
$leadID seems to be a php string. Make sure it gets printed in the right place. Also be aware of all the risks involved in passing your own strings around, like cross-site scripting and SQL injection vulnerabilities. There’s really no excuse for having Internet-facing production code not running on a solid framework.
Strings in Javascript (like in PHP and usually HTML) need to be enclosed in " or ' characters. Since you’re already inside both " and ', you’ll want to escape whichever you choose. \' to escape the PHP quotes, or &apos; to escape the HTML quotes.
<a /> elements are commonly used for “hyper”links, and almost always with a href attribute to indicate their destination, like this: Google homepage.
You’re trying to double up on watching when the user clicks. Why? Because a standard click both activates the link (causing the browser to navigate to whatever URL, even that executes Javascript), and “triggers” the onclick event. Tip: Add a return false; to a Javascript event to suppress default behavior.
Within Javascript, onclick doesn’t mean anything on its own. That’s because onclick is a property, and not a variable. There has to be a reference to some object, so it knows whose onclick we’re talking about! One such object is window. You could write Activate me to reload when anything is clicked.
Within HTML, onclick can mean something on its own, as long as its part of an HTML tag: <a href="#" onclick="location.reload(); return false;">. I bet you had this in mind.
Big difference between those two kinds of = assignments. The Javascript = expects something that hasn’t been run yet. You can wrap things in a function block to signal code that should be run later, if you want to specify some arguments now (like I didn’t above with reload): <a href="javascript:window.onclick = function () { window.open( ... ) };"> ....
Did you know you don’t even need to use Javascript to signal the browser to open a link in a new window? There’s a special target attribute for that: Google homepage.
Hope those are useful.
You should read up on the onclick html attribute and the window.open() documentation. Below is what you want.
<a href='#' onclick='window.open("http://www.google.com", "myWin", "scrollbars=yes,width=400,height=650"); return false;'>1</a>
JSFiddle: http://jsfiddle.net/TBcVN/
Use the onclick as an attribute of your a, not part of the href
<a onclick='window.open("lead_data.php?leadid=1", myWin, scrollbars=yes, width=400, height=650);'>1</a>
Fiddle: http://jsfiddle.net/Wt5La/

javascript function gets called twice

I am trying to call a javascript function on clicking a link. Actually i want to submit a form on clicking a link using post method so i am trying to do the below-
<a href="javascript:submitCategory(this)" >Handicrafts</a>
and in javascript
function submitCategory(varthis)
{
alert(varthis.value);
}
I have few important questions:
1>When i click on the link the function submitCategory gets called twice. After much analysis found that i had two js files included and removing one of them made the function getting called only once.
meaning
when i have included
<script type ="text/javascript" src="jquery.js"></script>
<script type ="text/javascript" src="cWed.js"></script>
submitCategory function gets called twice
and when i remove one of them and include
<script type ="text/javascript" src="jquery.js"></script>
submitCategory function gets called only once.
Why is it like this?
2> alert(thisvar.value) should return Handicrafts but it returns undefined. why could this be?
3>what exactly is the meaning of href="javascript:submitCategory(this)"? i have not come across this in any tutorial. and including this here should refer to the element "a" right?
1. You do not need to use the qualifier 'javascript:'
2. when you hook the event in html, always try to do it like event_handler(event). Note : event is the event object. and not some random variable here. You can read more about it in numerous places on the web. In your case varthis is the event object. to access this element use varthis.target and then to get its inner html you can use varthis.target.innerHTML
3. when the function is called you have to either explicitly get the html content of the calling element via the event tag, or just use jquery. You cannot pass variables in the way you think you are passing right now.
4. if you are actually trying to submit a form, I would recommend hooking the onSubmit event in script rather than HTML and put your custom form submit code there. If you do not need to do anything custom in form submission, you can just put the url of the target server function in the action attribute of the form.
Sample code :
<form>
Submit Category
</form>
<script type="text/javascript">
$('#submitCategoryLink').on('click', function (e) {
alert(e.target.innerHTML)
});
</script>
Since you haven't posted the contents of cWed.js it's difficult to know why you're getting a double submission, but my guess is that it contains a click handler of its own, which is duplicating the default handler.
The reason varthis.value doesn't work is because .value is only used for <input> and <select> elements, it contains the value that the user entered or selected from the menu. To get the text content of an element you should use .innerHTML.
A URI that begins with javascript: means that instead of fetching a page from a network location, the browser should execute the Javascript code after that prefix. It's not an officially recognized URI scheme (there was an Internet-Draft RFC, but it expired 2 years ago) , but all browsers support it.
When code is executing from a javascript: URI, this is the window, not the element that was clicked on. You need to use an onclick handler to get this set to the element.
The following works:
<a href="javascript:void(0)" onclick="submitCategory(this); return false;" >Handicrafts</a>
function submitCategory(varthis)
{
alert(varthis.innerHTML);
}
FIDDLE

javascript that produces functioning javascript

can you write javascript that produces/writes/etc. functioning javascript?
for example, have a link that has a function tied to it that when clicked produces a functioning javascipt snippet? The snippet could deal with a completely other elements.
For example
Link #1(has the javascript function that produces javascript) Link #2(does absolutely nothing for now)
Click on link #1(produces javascript snipped that says "when link #2 is clicked document.write('hello')"
Clicking on link #2 now produces "hello" whereas it previously did nothing. Is that possible?
Yes, you can dynamically assign event handlers described in text.
However, dynamic code generation is far more difficult than it sounds unless you're just following basic patters and replacing certain variables. Writing programs that write programs has long been a fascination of the computer industry, and this gave way to functional programming, which can be done in javascript.
Create the input/delete keys on the onClick handler for the datepicker, you can attach date information (or other data) when the input(s) are created. Now, you should look into $.delegate() for how to bind handlers to those inputs created. $.delegate can bind handlers to elements that are not created yet, so when they are created they will fire a handler. By storing date relevant information in the inputs via $.data() or data- attributes you will have context aware handlers for dealing with things.
If I understand your question correctly, you could do what you want with the code below.
Not sure why you'd want to do this, though.
can you write javascript that produces/writes/etc. functioning javascript?
You can do this the way I did it, or by using eval -- though, as many coders have pointed out, eval is evil!
<html>
<head>
<script type="text/javascript">
function initLinks(){
document.getElementById("link1").addEventListener("click", function(){
document.getElementById("link2").addEventListener("click", function(){
document.write("hello");
}, false);
}, false);
}
</script>
</head>
<body onload="initLinks()">
<a id="link1">Link 1</a>
<a id="link2">Link 2</a>
</body>
</html>

Invoking the HREF attribute of a link with javascript using javascript!

I never seen this before but you can invoke the HREF attribute of a link using javascript if the HREF contains javascript:;//code......;
On my example below click on both links. they do the same thing even though they have different javascript in the HREF.
for example:
<script type="text/javascript">
function clickme()
{
var link = document.getElementById("clickme");
eval(link.href);
}
</script>
<a id="clickme" href="javascript:alert('hello');">I will alert hello</a>
<br />
click me
I tested this on IE8, Firefox 3.6.8, Safari 5.0.1, and Chrome 6.0.472.55. Is this standardized, so I will not have to worry about this feature being deprecated in the future?
You don't have to worry about it being deprecated in the future. It's a bad idea now.
What's really happening there is this: There's a link using the javascript: protocol, which is respected by browsers. It means that everything following the javascript: is JavaScript and should be executed by the JS interpreter.
When you retrieve the link's href, you receive it as a string, e.g. "javascript:clickme()". You can use eval on strings to execute JavaScript. Now, you'd think that would fail (because of the javascript: protocol thing at the front), but it doesn't, because JavaScript has labels and that looks like a label when you treat it as JavaScript code.
So it works, but it's a bad idea. It's also disallowed (because of the eval) in the new "strict" mode of the latest version of JavaScript, ECMAScript 5th edition.
In general, when we think we need to use eval for something, it indicates that there's a problem with our code and that some refactoring is in order. The exceptions to that rule are very edgey edge cases that most of us will never run into. In this case, rather than having the href attribute contain the code that we want to execute, it should just use the code we want to execute. Your example, for instance, has a clickMe function as the only thing being used. Rather than evaling it, we should just call that function directly.
It won't be deprecated but I don't see the use of it.
If you do want to stream line this more do:
<script type="text/javascript">
function clickme()
{
clicked();
}
function clicked()
{
alert("hello");
}
</script>
<a id="clickme" href="javascript:clicked();">I will alert hello</a>
<br />
click me
Or better yet do:
Click Me
Or even better:
<span onclick="clicked();" class="MakeMeLookLIkeLInk">Click Me</a>
Anchor controls are mainly used for navigation, and as a good practice to keep it that way. if you have functionality that needs to take place, use a span/div with an onclick. You can use a button as well.
I think your question is whether the line
eval(link.href);
is valid.
The answer to that is yes, it is. There's no reason you can't evaluate code that's stored in some property, the same way you could evaluate the contents of an input box.
That said, this looks like a VERY bad way to code things. If you're not careful, you could end up in a circular loop. Additionally, code like this will be very hard to maintain.

Calling VBScript from Javascript

I've seen the related post on this, but it only covers using inline VBScript for onmouseover events, while calling a Javascript Function for the onClick.
Is there a way to call a VBScript Sub for the onClick event from a button that uses Javascript onmouseover and onmouseout events?
Currently when I try I get an error that the object does not support the property or method.
It is possible, but you will need to prefix all your script calls in HTML with the appropriate language.
onmouseover="javascript: vbfunction();"
If there are script calls that are not prefixed, you may get errors on the page as the parser doesn't know what scripting language is being used.
Put your code in the Head Tags: <head> </head>
Add your VBScript between these brackets:
<script type="text/vbscript">
</script>
Function myVBFunction()
' here comes your vbscript code
End Function
// From a hardcoded link, don't write a semicolon a the end:
link
You can read more about it here.
Make sure that the name of the sub you're calling doesn't match the ID of any other object in the script.

Categories

Resources