Calling js function in external js file - javascript

I'm trying to call a simple function with alert but it wont work when i try call the function (contained in an external js file) from my html page.
I have a import and the call is very simple. Any suggestions?
<head>
<script src="/js/jsFunctions.js" type="text/javascript"></script>
In my code I call
<a href="javascript:displayAlertText('someText');">
Inside the js I have some jquery followed by a function
function displayAlertText(someText)
{
alert('alert' + someText);
}

What you are doing looks like it should work. The problem is likely elsewhere.
Hrefs with "Javascript:" prefixes are really rather horrible. Instead, try rewriting that as:
<a href="#" onclick="displayAlertText('someText'); return false;">
Beyond that (which I don't think would actually be causing it), you've committed the cardinal sin of saying "It didn't work". Did you get any Javascript errors in the console? I suspect you would have, unless a valid function really was called.
Also, try calling the JS function explicitly from within a <script> block on your page, to see at what point it's failing.
Double-check as well that the external file really has been loaded at the time you click on the link - perhaps put a line at the bottom of the external script file to help check this, such as
alert('External file loaded.');
EDIT (based on comment): OK, so we've established you can call the method from "normal" JavaScript on your page. This means that the problem lies with the way that you're trying to call the script from your hyperlink.
Have you passed your HTML through a validator? If the syntax is invalid, then user agents can interpret it however they want, including ignoring it completely.
If the HTML does validate then at this point it might be useful to post a link to your full HTML, so that others can look over it and see where the problem lies. It's possibly something like another function overriding the onclick event for the link, and so your event handler gets lost.

In pure jQuery you would do this like:
$(document).ready(function(){
$('a').click(function(){
alert('here');
})
})

try this instead...
<a href="#" onclick="displayAlertText('someText');">
If that does not help, I would start making sure that your javascript file is loading correctly and doesn't contains some simple syntax error somewhere. View your page with Firebug on in Firefox and look for warnings and errors.

You mentioned jQuery. Is the function standalone or inside a jQuery object (i.e. wrapped inside another function)? This makes difference.
Apart from this problem, the way you invoke the function isn't clean. Move it to the onclick attribute or better make use of jQuery.

Related

How to make my page aware of a button that didn't exist on page load

I have an .aspx page and a separate .js file that contains all of my JavaScript and jQuery. The page also has a UserControl that doesn't exist on page load and that only appears when a certain button is clicked. And the UserControl contains, among other things, a JavaScript button.
The problem I'm having is connecting the newly-created JavaScript button that didn't exist on page load to my .js file.
At first I tried adding a jQuery select to get the button that lives inside the UserControl to the document.ready() that's in my existing .js file like this:
$(".TheClassOnMyUserControlButton").click(function () {
// do stuff here
}
But I couldn't get it to respond to anything I tried. So I put my jQuery inside a <script> tag in the UserControl page itself and the button suddenly started responding.
I have since come to understand that the reason the jQuery select wasn't working from the .js file is because the button didn't exist on page load and you can't select a thing that doesn't exist, and that makes sense now.
So my pseudo-newbie developer brain started trying to figure out how I could refresh the document.ready() in my .js file once the UserControl was on the page so that it would become aware of the newly-created UserControl and its buttons.
I asked another developer that I work with about it and they said to try bind.jquery without explaining how.
Googling that led me here as usual and I saw in the jQuery documentation that their bind() method has been deprecated and they suggest using on() instead.
I think I understand what the other developer meant and I know what I want to do, but I'm getting a little fuzzy on the details and I'm not exactly sure how to use on() to achieve what I'm trying to do.
I know I could just leave the <script> tag inside the UserControl, but I'd like to keep all my JavaScript and jQuery in one place if I can.
Does anyone have any suggestions or things I could try?
I appreciate any help anyone can offer.
Thanks
You have many options to bind an event to a button.
1.) simply write a function and bind it to the button on the event you want. For example:
<script>function doStuff(){
....
}
</script>
<button onclick="doStuff()">Do Something</button>
2.) You have to bind your function at the moment you have created the button. For example:
$('#Container').append('.button');
$('.button').on('event',doStuff);
For a more in depth answer i have to see your code
You can bind jQuery methods or events using the "on" method by looking at the entire document and then in the "on" method specifying the correct selector. Hope that makes sense. You can check the example below.
$(document).on("click", ".className", function (){ /*code here*/ });
Create the button beforehand and hide it. Then, show that button/section/panel on the event of other actions.
C# code behind
control.Visible = false;
control.Visible = true;
or
Jquery/bootstrap front end
$('#myElementID').addClass('hidden');
$('#myElementID').removeClass('hidden');

How to run on the page typed js

I'm currently working on a project which requires me to run by the user typed javascript in the form of a string.
I've tried adding an empty <script> tag to the html and appending the string (containing the users freshly typed (after the page was loaded) javascript) to this script tag but this doesn't work. (since the code inside the script tag will be run immediately after the page is loaded).
So I tried a different approach. I wrapped the js string inside of a function like so:
function runCode() { userString }
This is what the string I now append to the empty script tag looks like:
var code = "function runCode() { "+ userString +" }"
However this still doesn't work. The code (userString) shows up in the script tag according to the chrome dev tools, but trying to run the function causes the following error:
Uncaught ReferenceError: runCode is not defined
Does somebody know how this works? What is the proper way for me to do this?
Some background:
The project I'm working on is an online tool to draw using js. The goal here is to use the two.js library and link it to a modified textarea. (codemirror) Clicking the button will take your typed in code and use it to modify the two.js canvas on the other half of the screen.
This will make it easier to draw using the library, since you don't have to set up all the html, css and js files yourself, but instead you can focus on the code.
Note: The js you type into the textarea can by any valid js, so simple things as alerts, or even jQuery lines will work just fine.
Use eval() function.
However be aware that this is by design a HUGE hole of security.
You have to use eval(). Extract the user input from an onclick event and pass it into eval like so:
eval(userString)

Properly resolving variable in HTML

So I have a some HTML where I am pulling a value from a file and using it for a link, like so:
page
Now I need a popup to display that page when clicked, using a basic script and a line like this:
page
However, I need the popup page value to be pulled from the file as well, so something like this:
page
But the problem I am having is that the variable does not resolve in the popitup() call, I assume because of the apostrophes basically telling it to take that literally. What could fix this and make it resolve?
This is in conjunction with AngularJS
I'm going to assume that the first snippet you posted. If it works, great; this answer should work for you. If not, well, I don't know - more information would be needed, like a fiddle illustrating the problem or know what templating engine you're using.
Since the function "popitup" needs the save value as the href of the link, why not pass in the href of the link?
page
ngClick is the way to deal with that kind of things if you are using Angular.
This was anserwed here, and if you really need the onclick attribute: how to pass angular js variable inside onclick function as parameter

What is wrong with executing the JavaScript function at the end of the HTML instead of using body onload?

This is about calling the initialize function for the Google Maps API. I would prefer to call it at the end of the HTML instead of putting it in the body onload. It appears to be working, but is there anything wrong with this approach?
The Google API code I am referring to can be viewed at Place Autocomplete Address Form.
This is not a duplicate of window.onload vs <body onload=""/>.
Or this closed one, Unobtrusive JavaScript onload function.
It is closest to this one: Initializing JS components at the end of HTML or on "onload"?
However, my question is not generic.
That's just personal preference. Both ways work fine.
They probably used the onload handler because it appears to be more foolproof.
If the code was at the end of the file, some people might copy it and happily edit around without fully understanding why it is written at the end of the file and then later on shoot out a bunch of posts asking why their code isn't working.

What is href=javascript:;

in a code which i am goin through there is a link has href=javascript:; in code.when it is clicked it opens a lightbox to show some msg with close button.how is it done.I think this uses dojo
The code:
..
will actually do nothing. Generally this Nothing link allows some javascript code to use the onclick event instead. The onclick event triggers the window which may be from django or jquery or wherever.
EDITED:
i have just added this link that explane you how dojo work with onlclik event:
Dojo, how to do onclick event on a DIV
ok, just for the sake, all the answer here are good answer, in your particular case if you are using Dojo
the <a href="javascript:;" > simply prevent your <a> tag to jump around when clicked and of course have no action!
probably you have something like this in your code:
<a href="javascript:;" id="some" class="some_too" rel="some_too_too">
Dojo simply keep the <a> id OR class OR rel tags and execute the function!
href="javascript:somefunction();" is just a way to point to a function of some javascript code.
You can also do: href="#" onclick="somefunction();return false;"
Nothing really dojo about it. All it does is call the function or javascript code. It just tells the element to use javascript.
or href="javascript:void(0);" onclick="somefunction();" as stated already.
It's known as the javascript pseudo-protocol. It was designed to replace the contents of the document with a value calculated by JavaScript. It's best not to use it, for several reasons, including:
If JavaScript is disabled, you have a link that goes nowhere
If your JavaScript returns a value, the contents of the page will be replaced by that value
More reasons why you shouldn't use it
<a href="javascript:void(0)" onClick="callFunction();">
Call callFunction() method onClick
this can also be used as foollows
<a href="javascript:callFunction();">
<a href="#" onClick="callFunction();">
this also call javascript callFunction() method but it adds # in your URL to Avoid this Use
<a href="javascript:void(0)" onClick="callFunction();">
I believe this just indicates that your link is going to perform some javascript function. Usually you couple this by hooking up events on the link e.g. OnClick/OnMouseMove
All this does is make a call to a Javascript function which executes some Javascript. Maybe posting the code as an example helps.
Supposedly, it's a URL to a resource that's reachable via the "javascript" protocol, just like you can have "http:" or "ftp:". I don't know if it's an actual standard but most browsers understand that the URL must be fed to the JavaScript interpreter. So, in practice, you can use it to have JavaScript code that's triggered by a link, e.g.:
Say hello
Of course, writing your JavaScript code inside HTML tags is neither clean nor mantainable. But the possibility exists.
What about href="javascript:;"? If you pay close attention, you'll realise that ";" is a JavaScript code snippet that, well, does nothing. That's the point. This is often used to have a link that points nowhere. The main purpose is that clicking on it triggers JavaScript code defined somewhere else (via onclick event handlers).
Last but not least, you often see stuff like onclick="javascript:doStuff()". The onclick HTML attribute expects Javascript code, not a URL. In this situation, the javascript: prefix is totally superfluous. However, the code still runs. It happens to be a label in JavaScript syntax just by chance ;-)

Categories

Resources