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.
I have a very strange issue preventing my code from firing a JQUERY function - but only if the event is declared in an onclick attribute tag within the page's html. If that same function is assigned to an element with a javascript ".click(function()..." event, then the function is called properly and the code doesn't say "This event doesn't exist!", essentially.
I trawled through the internet looking for someone with the same issue, and while there are a lot of questions that look superficially like the issue I am having, none seem to address it exactly.
Here is an example:
//Delete an existing exclusion.
$.fn.deleteExclusion = function (idExclusion) {
document.cookie = idExclusion + "=; expires=; path=/";
$.fn.buildExclusions();
}
If I call this method by saying:
$("#someButton").click(function(){
$.fn.deleteExclusion();
)
... then the function exists and is run properly.
However, if I assign this function as follows (created on page load as part of page html):
Some Button
... then the function doesn't exist when I click that link.
This does not happen for one of my company's websites, which uses ASP.NET .aspx page structures. However, I am working on a new MVC application, which is where this behavior is occurring.
I am stumped, frankly. Right now, I am not sure what else to provide code-wise to demonstrate, without probably overdoing it with unnecessary details. Please let me know if you need additional code to help me figure this out.
You need to include Jquery
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
jQuery(document).ready(function($){
$.fn.deleteExclusion = function (idExclusion) {
document.cookie = idExclusion + "=; expires=; path=/";
$.fn.buildExclusions();
}
});
We found a workaround. To get this working, we added:
//Set onclick events for delete exlusion anchor tag buttons created dynamically.
$(document).on("click", "a.deleteExclusion", function () {
$.fn.deleteExclusion($(this).attr("id").replace("delete", ""));
});
This created the onclick event on page load, but applied it to elements as they were created. It allowed elements created in our cshtml file initially, along with dynamically created html elements, to have a working click event.
I'm trying to use a script called Socialite in my Wordpress site to make social share buttons appear only after the user has moved his/her mouse AND the document already loaded.
I can't get it to work together. My current script, that does work, is:
jQuery(document).one("mousemove", function() {
var social_container = jQuery('.social_buttons');
Socialite.load(social_container);
});
But how do I connect the document load part?
Thanks
Have you tried to put your code into
jQuery(document).ready(function(){/* your code goes here*/});
?
For starters you have a small typo in the first line
jQuery(document).one("mousemove", function() {
You're calling .one("mous...
It should be .on("mous...
Next considerations is that the document ready statement below will happen before images etc have loaded
$(document).ready(function(){
// your code goes here.....
});
using a window load statement like below waits until everything i.e.images have loaded in full
$(window).load(function(){
// code here.....
});
I'm not sure what would suit your needs best as I have no experience with Socialite but hopefully this will give you the answers you need.
Hello I'm writing a jQuery code for my application and got some issues (like function called once, running three times).
I must know if exist any site that people audit source code and comment my mistakes..
most of my code is like this i/e:
$('a.openBox').click(function(){
//do something
$('.box').show();
$('a.openModal','.box').click(function(){
$.openModal(some, parameters)
});
});
$.openModal = function(foo,bar){
//do something
$('a.close').click(function(){
$('#modal').hide();
});
$('input.text').click(function(){
$.anotherFunction();
});
});
does am I doing something obviously wrong?
I'm not aware of any source code audit like that -- certainly not for free! This website is pretty good for specific problems though...
In this case, the problem is that you are continually binding more and more events. For instance, with the following code:
$('a.openBox').click(function(){
//do something
$('.box').show();
$('a.openModal','.box').click(function(){
$.openModal(some, parameters)
});
});
This code says "whenever the user clicks on an a.openbox element, show all .box elements and bind a new click handler to all .box a.openModal elements". This means that you will add another handler to .box a.openModal every time you click on a.openbox. I can't believe this is what you want to do!
It is difficult to work out what the correct code should be without knowing the context and exactly what you want to happen. My advice for you in the first instance would be to do some reading up on Javascript events and event handlers, particularly as they are implemented in jQuery.
I have a couple of, what may end up being for this forum, overly-novice questions regarding unobtrusive event handling.
As I understand it, a properly set-up document would look something like this:
<html>
<head>
<title>Title</title>
<script src="jsfile.js" type="text/javascript></script>
</head>
<body>
//Body content, like some form elements in my case
</body>
</html>
Jsfile.js would look something like this:
function a() {
//code;
}
function b()...
window.addEventListener('load', a, false);
document.getElementById("id").addEventListener('click', b, false);
document.myForm.typeSel.addEventListener('change', c, false);
//or to use better browser-compatible code...
function addEvent(obj,evt,fn) {
if (obj.addEventListener)
obj.addEventListener(evt,fn,false);
else if (obj.attachEvent)
obj.attachEvent('on'+evt,fn);
}
addEvent(window, 'load', a);
addEvent(document.getElementById('id'), 'click', b);
addEvent(document.myForm.typeSel, 'change', c);
As I understand it, while in the head the browser will load this JavaScript code, adding each of those event handlers to their respective elements. HOWEVER... While the window handler is added properly, none of the others are. But if placed within a function, the (for instance) getElementById method of accessing an element works just fine, and the event handler is added. So I could conceivably make a loadEvents() function which is called via window onload, which contains all of the addEvent() functions for the other document elements for which I need event handlers. But as I understand the whole thing, I shouldn't have to do this.
In addition, if I were to stick the addEvent code within the body along with the element it addresses, such as:
<input type="checkbox" id="test" />
<script type="text/javascript>
document.getElementById("test").onclick = func;
</script>
...then it works fine. But of course it also violates the whole reason for removing inline event handlers!
So question being: In order to use *element*.addEventListener('click',func,false), addEvent(*element*,'click',func), or even *element*.onclick = func - how can I successfully reference an element at the end of a script file in the head, without having to stick it in another function? Why does getElementById and other such methods not work outside of a function in the head?
Or, is there some flaw in my underlying understanding?
Putting <script> in the <head> used to be the wisdom. But nowadays, with heavy ajax pages, <script> is more and more often but in the body, as far down below as possible. The idea is that the loading and parsing of the <script> keeps the rest of the page from loading, so the user will be looking at a blank page. By making sure the body is loaded as fast as possible, you give the user something to look at. See YAHOO best practices for a great explanation on that issue: http://developer.yahoo.com/performance/rules.html
Now, regardless of that issue, the code as you set it up now, can't work - at least, not when the elements you attempt to attach the handlers to aren't created yet. For example, in this line:
document.getElementById("id").addEventListener('click', b, false);
you will get a runtime error if the element with id="id" is inside the body. Now, if you put the <script> in the body, way below, after the content (including the lement with id="id", it will just work, since the script is executed after the html code for those elements is parsed and added to the DOM.
If you do want to have the script in the head, then you can do so, but you'll need to synchronize the adding of the event handlers with the rendering of the page content. You could do this by adding them all inside the document or window load handler. So, if you'd write:
//cross browser add event handler
function addEventHandler(obj,evt,fn) {
if (obj.addEventListener) {
obj.addEventListener(evt,fn,false);
} else if (obj.attachEvent) {
obj.attachEvent('on'+evt,fn);
}
}
addEventHandler(document, 'load', function(){
//set up all handlers after loading the document
addEventHandler(document.getElementById('id'), 'click', b);
addEventHandler(document.myForm.typeSel, 'change', c);
});
it does work.
The reason why window.addEventListener works while document.getEle...().addEventListener does not is simple: window object exists when you're executing that code while element with id="abc" is still not loaded.
When your browser downloads page's sources the source code is parsed and executed as soon as possible. So if you place script in head element - on the very beginning of the source - it's executed before some <div id="abc">...</div> is even downloaded.
So I think now you know why
<div id="test">Blah</div>
<script type="text/javascript">document.getElementById("test").style.color = "red";</script>
works, while this:
<script type="text/javascript">document.getElementById("test").style.color = "red";</script>
<div id="test">Blah</div>
doesn't.
You can handle that problem in many ways. The most popular are:
putting scripts at the end of document (right before </body>)
using events to delay execution of scripts
The first way should be clear right now, but personally I prefer last one (even if it's a little bit worse).
So how to deal with events? When browser finally download and parse whole source the DOMContentLoaded event is executed. This event means that the source is ready, and you can manipulate DOM using JavaScript.
window.addEventListener("DOMContentLoaded", function() {
//here you can safely use document.getElementById("...") etc.
}, false);
Unfortunately not every browser support DOMContentLoaded event, but as always... Google is the anwser. But it's not the end of bad news. As you noticed addEventListener isn't well supported by IE. Well... this browser really makes life difficult and you'll have to hack one more thing... Yes... once again - Google. But it's IE so it's not all. Normal browsers (like Opera or Firefox) supports W3C Event Model while IE supports its own - so once again - Google for cross-browser solution.
addEventListener might seems now the worst way to attach events but in fact it's the best one. It let you easly add or remove many listeners for single event on single element.
PS. I noticed that you consider of using Load event to execute your scripts. Don't do that. Load event is execute too late. You have to wait till every image or file is loaded. You should use DOMContentLoaded event. ;)
EDIT:
I've forgotten... dealing with cross-browser event model is much easier when you're using some framework like very popular jQuery. But it's good to know how the browsers work.
are you familiar with jQuery?
its a javascript library featuring some really awesome tools.
for instance if you want to have some js action done just after your page if fully loaded and all DOM elements are created (to avoid those annoying exceptions) you can simply use the ready() method.
also i see you want to attach click \ change events jQuery takes care of this too :) and you don't have to worry about all those cross-browser issues.
take a look at jQuery selectors to make your life easier when attempting to fetch an element.
well thats it, just give it a shot, its has a very intuitive API and a good documentation.