Function is not found in Jquery, but is found in Javascript - javascript

I have an html document in which a function is called like this
<div id="mon" class="topbar" onclick="verd()">
This calls a jquery function inside the body tag that goes like this
<script src="jquery.js">
function verd(){
$("#stillmain").empty();
} </script>
This returns the error:
Uncaught ReferenceError: verd is not defined
at HTMLDivElement.onclick
When I change the script to pure Javascript without Jquery however like this
<script>
function verd(){
$("#stillmain").empty();
} </script>
it does recognize the function verd(), can anyone explain what is going on, and how I could still use Jquery?
I am using the newest version of Jquery(just changed the name, nothing else).

When you give a script tag a src attribute it's going to load that source file in place of the script contents. So any script tags with a src should be kept empty.
You need to load jQuery by calling a script tag with its source on it, and then in a separate tag you can make your own script tag and write your custom JavaScript there.
<script src="jquery.js"></script>
<script>
function verd(){
$("#stillmain").empty();
}
</script>
Make sure that your custom scripts are loaded after jQuery.

If you want to run this as a jQuery function you need to use the proper syntax. Try the link below.
How to Create a jQuery Function
Also, you need to load jQuery in a separate tag or else none of your code will be ran other than the source of that script!

Related

Alternative to hide/show content with JS?

is there a better way to replace this kind of js function by simply collapse/toggle a div and show/hide its content?
$(function() {
$('#destselect').change(function(){
$('.dest').hide();
$('#' + $(this).val()).show();
});
});
The reason this is happening is because your js file is called on the head of your page.
Because of this, when you document.getElementsByClassName('collapsible');, colls result in an empty array, as your elements in body are not yet created.
You could either create a separate js file and add it at the end of your body (in that way you make sure your colls are created when your javascript is executed), or just wrap your code on a DOMContentLoaded event listener that will trigger your code once the document has completely loaded.
My guess would be that you are loading your script before browser finishes loading dom conetent and so when it runs the elements it is trying to add event listeners to, don't yet exist.
Try wrapping all you javascript in that file in this:
document.addEventListener("DOMContentLoaded", function(event) {
// all your code goes here
});
The above makes sure that your script is run after loading all elements on the page.
You could add a script tag to the header of your HTML file, this will import the JS file into your current page as follows
<script src="File1.js" type="text/javascript"></script>
Then call the function either in onclick in a button or in another script (usually at the bottom) of your page. Something like this:
<body>
...
<script type="text/javascript">
functionFromFile1()
</script>
</body>
Seems like your script is not executing properly due to a missing variable.
In this script https://www.argentina-fly.com/js/scripts.js
Naves variable in function UpdateDetailsDestination() is not defined.
I think you should resolve this first and then check your further code is working on not.
Please take a look into Console when running page. You'll see all JavaScript related errors there.

javascript function not accessible from external file

This might be a stupid beginner's problem, but it's driving me mad. Simplified, the code is:
I have an index.php where in an inline script (located in the head element), some JS functions are defined.
<script type="text/javascript">
$(function(){
// other code
var popup = function(message,color){
$(".title").css({"color": "beige" });
$(".popup_alert").css({"background-color": color});
$( ".popup_alert" ).append(message);
$(".popup_alert").removeClass("offscreen").delay(800).queue(function(){
$(this).addClass("offscreen").dequeue();
$(this).empty();
$(".title").css({"color": "#444" });
});
};
};
</script>
At the very bottom of the <body>, I'm loading an external JS file where some JQuery happens:
<script src="ajaxToDB.js" type="text/javascript"></script>
JQuery is not the problem. It's loaded and the other functions inside this external file are working.
Inside this linked file, I can't call the function defined in the index.php.
popup("test",orange);
Will yield a console error "Uncaught ReferenceError: popup is not defined"
Is this normal? I already wrapped all the stuff in ajaxToDB.js inside a
$(function() { ... }); I read that this would force the page to load first, but to no avail...
What's the stupid detail I overlooked?!
Thanks to #guest271314, I learned a lesson in JS structure:
Previously, I had wrapped the entire code within the main document's script tag inside a $(function(){}; This I thought, was "necessary" as the script tag was placed inside the head element, and the document otherwise wouldn't have been ready.
When using another, external JS file however, this technique now prevented the external code from referring to functions declared inline, as these now "waited" for the rest of the document to be ready, including the external file (which then referred to a yet undeclared / "pending" main function).
Wow.
Removing the $(function(){}; wrap and moving the script element to the bottom of the body resolved the issue. I guess that's where it should've been in the first place... level up

executing javascript function from HTML without event

I wish to call a javascript function from an HTML page and I do not want it dependent on any event. The function is in a separate .js file since I wish to use it from many web pages. I am also passing variables to it. I've tried this:
HTML:
<script type="text/javascript" src="fp_footer2.js">
footerFunction(1_basic_web_page_with_links, 1bwpwl.html);
</script>
The function in fp_footer2.js:
function footerFunction(path, file) {
document.write("<a href=" + path + "/" + file + " target='_blank'>Link to the original web page for this assignment.</a>");
return;
}
(I have also tried putting the fp_footer2.js file reference in the header, to no avail. I'm not sure if I can put it 'inline' like I did in this example. If not, please let me know.
PS: I know I can do this with a simple 'a href=""' in the HTML itself. I wanted to see if this could work, for my own curiosity.
If a <script> has a src, then the external script replaces the inline script.
You need to use two script elements.
The strings you pass to the function also need to be actual strings and not undefined variables (or properties of undefined variables). String literals must be quoted.
<script src="fp_footer2.js"></script>
<script>
footerFunction("1_basic_web_page_with_links", "1bwpwl.html");
</script>
JavaScript will run while your page is being rendered. A common mistake is to execute a script that tries to access an element further down the page. This fails because the element isn't there when the script runs.
So includes in the <head> will run before any DOM content is available.
If your scripts are dependent on the existence of DOM elements (like a footer!) try to put the script includes after the DOM element. A better solution is to use the document ready event ($(document).ready() in jQuery). Or window.onload.
The difference between documen ready and window onload is that document ready will fire when the DOM has been rendered; so all initial DOM elements will be available. Where as window onload fires after all resources have loaded, like images. window onload is useful if you're doing things with those images. Usually document ready is the right one.
Maybe I misunderstand your question, but you should be able to do something like this:
<script type="text/javascript" src="fp_footer2.js"></script>
<script type="text/javascript">
footerFunction(1_basic_web_page_with_links, 1bwpwl.html);
</script>
Have you tried calling it from a document.ready?
<script type="text/javascript">
$(document).ready(function() {
footerFunction(1_basic_web_page_with_links, 1bwpwl.html);
});
</script>

Execute JavaScript code at the end when the HTML has been loaded

I want to execute a function at the end when the HTML has been loaded. I tried it with onload without success. I also tried it with ready, but it still doesn’t work. Here is my code. This is again placed in the header:
<script type="text/javascript">
$(document).ready(function() {
$('#infowindow_content').html('test');
});
</script>
The div is also set by an external JavaScript file. Content:
window.onload = initialize;
function initialize() {
document.getElementById('infowindow_content').innerHTML = 'testa';
}
It is included the following way before the closing body tag:
<script type="text/javascript" src="../lib/functions.js"></script>
I tried to place the above code before the closing body tag, but currently I have no idea why this doesn't work (the content isn't changed by my JavaScript code). If I execute it on the console afterwards everything works fine.
Solution:
I set a configuration parameter (language) in the HTML file. In the JavaScript file I ask for this value and depending on the value I define another content. Sometimes it could be so simple ...
Try this:
setTimeout(function() {
$(document).ready(function() {
$('#infowindow_content').html('test');
});
}, 20);
I don't know the jQuery equivalent but try the native JS.
Since the <body> has the most HTML & loads after <head>...
document.body.onload=function(){
yourFunction(args)
}
<body onload="yourFunction(args)">...</body>
Or maybe the window object, since it's the root of every webpage DOM...
window.onload=function(){
yourFunction(args)
}
Always place DOM manipulating code directly before your </body> tag. JavaScript in the header should only be called to libraries, such as jQuery.

Jquery event handling code doesnt work after including script in head from an external js file

I included a script into my document's head that contains the following jquery code:
$('.unappreciatedIcon').click(function() {
alert('JS Works!');
});
In the body of my document I have following:-
<span class="unappreciatedIcon">.....</span>
But there is no alert displayed when I inserted the script into the document head from an external js file. When I had put this script in body simply below the target elements this worked flawlessly.
Thanks to you all:
I am getting this to work with the following code:
$(document).ready(function(){
$('.unappreciatedIcon').click(function() {
alert('fds');
})
});
Did you wrap your jquery in a $(document).ready(function() { // your code // }); ?
If not your jquery code is executing immediately and the browser has not loaded your span. You need to wait for the document to be ready (using the code above) before assigning events.
Update
$(document).ready(function() {
$('.unappreciatedIcon').click(function() {
alert('JS Works!');
});
});
When your script ran, it looked for an element having the class unappreciatedIcon. Nothing was found because the document is still being parsed and there was no node having the class unappreciatedIcon available in the document so far. The DOM is being constructed incrementally.
But when you put your script after the span element occurs, then $('.unappreciatedIcon') was found because it has been parsed and added to the DOM, so the click handler was tied to it.
Either run your code in a ready callback. The ready callback basically runs when the entire HTML has been parsed and the DOM is fully constructed which is usually a safe point to start running your JavaScript code that depends on the DOM.
$(document).ready(function() {
$('.unappreciatedIcon').click(...)
});
or put your code after the element occurs (don't need to wrap it inside the ready callback in this case),
<span class="someClass">..</span>
..
<script>
$('.unappreciatedIcon').click(...)
</script>
just going to go with basics but did you make sure to include the jquery library? If it doesn't work and it's in the code you can also open in firefox with firebug go to the console tab and see what error you have.
The javascript is being processed before the page has finished rendering. As Erik Philips suggested, you need to put this statement inside your $(document).ready() function to ensure the page is loaded before the statement is evaluated.
$(document).ready(function(){
$('.unappreciatedIcon').click(function() {
alert('JS Works!');
});
});
here is the fiddle http://jsfiddle.net/Pf4qp/
Since HTML loads from top to bottom, the head loads before the rest of the page. You could solve this problem by putting the link to your js file right before the end tag. However, its generally better practice to put the javascript link in the head.
A better alternative is to use the defer attribute in the script tag.
For example:
<script type="text/javascript" src="script.js" defer></script>
or
<script type="text/javascript" src="script.js" defer="defer"></script>
The second option is kind of unneccessary though. This attribute is pretty well supported. Internet Explorer has supported it since version 5.5 though apparently it is "buggy" through IE9. It has been fully supported since FireFox 3.5, Chrome 8.0, Safari 5.0. It also works with all current mobile browsers. I guess it is not supported by any Opera browsers though.

Categories

Resources