jquery event trigger not working - javascript

I have two scripts.
The first script holds a prototype class of a game. This class is with use strict and isn't surrounded by document ready. The trigger:
$("#trigger").trigger("noPossibilities");
In the second script, which also has use strict, I try to catch the trigger:
$(document).ready(function() {
$("#trigger").on("noPossibilities", function() {
console.log("noPossibilities trigger");
});
});
The problem is that I can't catch the trigger. This has probaly something to do with use strict/scope but I can't seem to find a way around this.
Really hope someone can help me
UPDATE
The first script has a prototype class.
This class is getting instantiated in the second script. After the handler. Then it still doesn't work because the first script is loaded before the second script?
Also when I execute this line from the console:
$("#trigger").trigger("noPossibilities");
It doesn't get triggered. Shouldn't it work this way?
UPDATE 2
I found the problem. The first script adds the element with id trigger to the document when it is instantiated. I have a popup at the beginning of the game. Now the handler is getting attached on the click of that button.
The document probaly didn't have the element on which the handler should have gotten attached to. Now it is being attached later on and now it's working.

The issue is not with the scope, you are triggering the event before the handler is attaching to the element. The code inside document ready handler executes only after the DOM elements are loaded. In case you are triggering immediately after the script then it won't work since the elements are still loading.
You can check the working of triggering within a different context by moving it to another document ready handler(to execute only after handler attached).
$(document).ready(function() {
$("#trigger").on("noPossibilities", function() {
console.log("noPossibilities trigger");
});
});
$(document).ready(function() {
$("#trigger").trigger("noPossibilities");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="trigger"></div>

Related

When to use $(function() {}) when registering click handlers with jQuery?

What is the difference between
$(function()
{
$(".some").click(function()
{
...
});
});
and
$(".some").click(function()
{
...
});
I know from here that $(function() is shorthand for $(document).ready(function(). But why are we waiting for the document to be ready? Will the function not be only called when some is clicked anyway?
Note: #2 does not work in my case.
The difference is that #1 waits for the DOM to fully load before running the JavaScript.
The second code runs the JavaScript when it receives it which means it looks for .class elements before they have finished loading. This is why it doesn't work.
You need the document to be ready, i.e. all elements of the document to be available, before you can add an event listener to an element.
The reason is: consider a button, and you want an event listener (listening for the click event, for example.
When your sript runs but the button is not yet present, the attempt to attach the listener will fail. As a result, the associated function cannot be called once the button is actually clicked.
Does that answer your question?
You use the $(function()) simply because you need the DOM to fully load.
For example you have a button and you want to add some action on click. You click the button, but nothing happened, because the button was handled prior to the DOM loading.
If you won't check that the DOM is fully loaded, some unexpected behavior might occur.
Please do not confuse between onload() to ready(), as on load executes once the page is loaded and ready() executes only when the DOCUMENT is fully ready.
$(function(){...}) triggers the function when the DOM is load, it's similar to window.onload but part of jquery lib.
you can also use $(NAMEOFFUNCTION);
It's there to be sure the event has a element to listen to.

Target HTML generated by Javascript?

I have a slider button created using a JavaScript plugin, which automatically generates an element with class name .flex-next. However, when I run the following code, nothing is logged in my console:
$(window).load(function() {
$( ".flex-next" ).on( "click", function() {
console.log("youclick");
})
});
Since the button is added dynamically after the dom is loaded, you need to use event delegation so the click event can be used on this button:
$(document).on('click','.flex-nex',function() {
console.log("youclick");
})
Your setting your call to fire when the window loads by using $(window).load(...);. A flexsider is initiated on $(document).ready(...) which happens after the window loads and all of the content is loaded into the DOM. So when your script fires, it looks for an element that isnt there yet.
Get around this by firing your script on $(document).ready(), and use event delegation. The best practice way is to declare your function like so:
$(document).ready(
$(document).on('click', ".flex-next", function() {
console.log("youclick");
});
});
this way your click listener will wait until the page is ready and will put a click event on to any .flex-next event, even those created dynamically. That way if your using large imagery that is loaded asynchronously the code will still work.
You are probably calling your $(".flex-next").on call before the slider button has been executed. So, basically, your .flex-next class doesn't exist in the DOM yet when you call the .on
You should call the .on call after plugin has been initialized.

jQuery document.ready

I am a little confused with document.ready in jQuery.
When do you define javascript functions inside of
$(document).ready() and when do you not?
Is it safe enough just to put all javascript code inside of $(document).ready()?
What happens when you don't do this?
For example, I use the usual jQuery selectors which do something when you click on stuff. If you don't wrap these with document.ready what is the harm?
Is it only going to cause problems if someone clicks on the element in the split second before the page has loaded? Or can it cause other problems?
When do you define javascript functions inside of $(document).ready() and when do you not?
If the functions should be globally accessible (which might indicate bad design of your application), then you have to define them outside the ready handler.
Is it safe enough just to put all javascript code inside of $(document).ready()?
See above.
What happens when you don't do this?
Depends on what your JavaScript code is doing and where it is located. It the worst case you will get runtime errors because you are trying to access DOM elements before they exist. This would happend if your code is located in the head and you are not only defining functions but already trying to access DOM elements.
For example, I use the usual jQuery selectors which do something when you click on stuff. If you don't wrap these with document.ready what is the harm?
There is no "harm" per se. It would just not work if the the script is located in the head, because the DOM elements don't exist yet. That means, jQuery cannot find and bind the handler to them.
But if you place the script just before the closing body tag, then the DOM elements will exist.
To be on the safe side, whenever you want to access DOM elements, place these calls in the ready event handler or into functions which are called only after the DOM is loaded.
As the jQuery tutorial (you should read it) already states:
As almost everything we do when using jQuery reads or manipulates the document object model (DOM), we need to make sure that we start adding events etc. as soon as the DOM is ready.
To do this, we register a ready event for the document.
$(document).ready(function() {
// do stuff when DOM is ready
});
To give a more complete example:
<html>
<head>
<!-- Assuming jQuery is loaded -->
<script>
function foo() {
// OK - because it is inside a function which is called
// at some time after the DOM was loaded
alert($('#answer').html());
}
$(function() {
// OK - because this is executed once the DOM is loaded
$('button').click(foo);
});
// OK - no DOM access/manipulation
alert('Just a random alert ' + Math.random());
// NOT OK - the element with ID `foo` does not exist yet
$('#answer').html('42');
</script>
</head>
<body>
<div id="question">The answer to life, the universe and everything</div>
<div id="answer"></div>
<button>Show the answer</button>
<script>
// OK - the element with ID `foo` does exist
$('#answer').html('42');
</script>
</body>
</html>
The document.ready handler is triggered when the DOM has been loaded by the browser and ready to be manipulated.
Whether you should use it or not will depend on where you are putting your custom scripts. If you put them at the end of the document, just before the closing </body> tag you don't need to use document.ready because by the time your script executes the DOM will already be loaded and you will be able to manipulate it.
If on the other hand you put your script in the <head> section of the document you should use document.ready to ensure that the DOM is fully loaded before attempting to modify it or attach event handlers to various elements. If you don't do this and you attempt to attach for example a .click event handler to a button, this event will never be triggered because at the moment your script ran, the jQuery selector that you used to find the button didn't return any elements and you didn't successfully attach the handler.
You put code inside of $(document).ready when you need that code to wait for the DOM to load before executing. If the code doesn't require the DOM to load first to exist, then you can put it outside of the $(document).ready.
Incidentally, $(function() { }) is short-hand for $(document).ready();
$(function() {
//stuff here will wait for the DOM to load
$('#something').text('foo'); //should be okay
});
//stuff here will execute immediately.
/* this will likely break */
$('#something').text('weee!');
If you have your scripts at the end of the document, you dont need document.ready.
example: There is a button and on click of it, you need to show an alert.
You can put the bind the click event to button in document.ready.
You can write your jquery script at the end of the document or once the element is loaded in the markup.
Writing everything in document.ready event will make your page slug.
There is no harm not adding event handlers in ready() if you are calling your js functions in the href attribute. If you're adding them with jQuery then you must ensure the objects these handlers refer to are loaded, and this code must come after the document is deemed ready(). This doesn't mean they have to be in the ready() call however, you can call them in functions that are called inside ready() themselves.

jquery click listener on remote javascript file

I have a simple link:
Test Link
I want to get an alert whenever this link is pressed, so I add:
<script>
$('#test').click(function() { alert('clicked!'); } );
</script>
and it works fine, but when i move this code to a remote javascript file, it doesn't work..
any idea why?
I've also tried this code:
$(document).ready(function() {
$('#test').click(function() { alert('clicked!'); });
});
Your second example, using the ready function, should be working. Your first example should also work provided you include the script below the element with the ID "test" (the element has to already exist when your script runs, since you're not waiting for DOM ready). In both cases, your script must be included below (after) the jQuery script.
Example when you don't use ready
Example when you do use ready
I'd check that your external file is actually getting loaded (look for 404 errors in the browser console).
Update: From your comment below, the problem is that the "test" element doesn't exist when you're trying to hook up the handler. click only sets up the handler on the element if it already exists. If you're creating the element later, you have three options (two of which are really the same):
Use the code you already have, but run it after you've created the element (e.g., in the success callback of the ajax call you're making).
Use live, which basically hooks the click event document-wide and then checks to see if the element you tell it ("#test", in this case) was clicked.
Use delegate on the appropriate container (the element within which you're adding "test"). delegate is a more targeted version of live.
live and delegate are both examples of a technique called event delegation, which jQuery makes easy for you by providing those methods.
See the links for further information and examples, but for example, suppose you're going to be adding the "test" element to an element with the ID "target". You'd use delegate like this:
$("#target").delegate("#test", "click", function() {
alert("Clicked");
});
That hooks the click event on "target", but acts a lot like you've just magically hooked it on "test" as soon as "test" was added. Within your handler, this refers to the "test" element just as with click.

Jquery/Javascript

Good morning peoples.
I have a bit of a slight jQuery question/problem that I am not sure how to tackle.
I have a click handler bound to varying classes on some anchor tags (which works great). I have now come to a page that needs an extra handler on the same anchor tags so I decided to use some namespacing to get the desired result. The trouble with the namespacing is that it is called before the original click handler and creates problems with the first handler. The error is raised due to the first handler requiring an element to exist to continue in the function but the namespaced click handler removes the element before so it errors out.
Does anyone know if one can tell namespaced handlers to execute After the original handler or would I have to completely re-write the script and perhaps extend it on this one (and only) page to have the funcitonality work as I would like.
Thanks in advance.
Alex
It's easier to add a classname to the anchors on the page that events are bound on and check that in my function..
Sorry for any time wasted
If you bring the handler out into a separate function, you can call the original handler from the other handler.
function handler() {
// original event handler code
};
$('#originalTarget').click(handler);
$('#otherTarget').click(function() {
// code to do anything specific to this handler
handler();
}
You can assign more than one handler:
// general handler
$('a.linkclass').click( function(){
doThis();
});
// specific handler on the page in question
$('#specificlink').click( function(){
doSomethingExtra();
});

Categories

Resources