applying script to elements inserted via jquery .html() - javascript

i'm kinda new to scripting so this might be a bit basic, but i couldn't find an answer anywhere.
To improve my webpage loading time I made some HTML element load (via AJAX) and inserted only when a certain button is clicked, using the jquery .html() function.
That worked, but now all the jquery commands which referred to that element don't seem to apply. I'm guessing it's because the original commands were loaded before the new HTML?
For example, code like this:
$(document).ready(function(){
$('#myButton').click(function(){
$('#placeHolder').html('<div id="touchMe">click me</div>');
});
$('#touchMe').click(function(){
alert ("WORKED");
});
}
How do I make the #touchMe.click command apply to the new incoming HTML?
thanks a lot

Take a look at live()
$('#touchMe').live('click', function() {

Try -
$('#touchMe').live('click',function(){
alert ("WORKED");
});

Instead of
$('#touchMe').click(function(){
alert ("WORKED");
});
use
$('#touchMe').live('click', function(){
alert ("WORKED");
});

you use .live() or .delegate() function instead of click.
$(document).ready(function(){
$('#myButton').live('click', function(){
$('#placeHolder').html('<div id="touchMe">click me</div>');
});
$('#touchMe').live('click', function(){
alert ("WORKED");
});
}
note: the live on "mybutton" is not necessary in this example.

Related

How to use multiple handlers in jquery function

I have some code I am working on and I cannot seem to figure out the terms to search for assistance.
I am trying to add a jquery statement that executes when the #quickSearchResults_section is clicked "AND" when #nav-input is focused out.
So in a nutshell, I am still learning jquery and programming logic and want to use click function and focusout.
<script>
$(":not(#quickSearchResults_section)").click(function(){
$("#quickSearchResults_section").hide();
});
</script>
Try something like this:
$("#nav-input").on("blur", function(){
$("#quickSearchResults_section").click(function(){
$("#quickSearchResults_section").hide();
});
});

JavaScript alert callback not working inside a function

I am trying to make a image preview containing of about 5-6 images which will appear one after another when user hovers over it (not like a carousel with prev and next buttons). Here is the fiddle consisting of what I gathered so far.. i don't know if this approach is right or not.. but I am stuck as the alert callback is not working. Could someone please tell me what is wrong?
$(function()
{
var imageCount = $('#product_grid_list').find('figure')[0].getElementsByTagName('img');
for (var i = 0, n = imageCount.length; i < n; i++) {
imageCount[i].on('click', function(e)
{
alert('Everything is going fine!');
}
);
}
}
);
The root cause of click event callback can't be triggered is that you're trying to register a event handler on a "DOM" (in this case: imageCount[i]) element in jQuery way. Try to register the event handler like this if you want to use pure javascript solution:
imageCount[i].addEventListener('click', function(e){
alert('Everything is going fine!');
});
Here is a jsfiddle demo.
Note: I didn't consider the cross browser issue in this case.
BTW, try to cache the length of imageCount node list, it will improve the performance.
You are using js AND jQuery at same time. It's wrong. If you use jQuery, than click event will be like this:
$(document).('click', '#product_grid_list figure img', function(){
alert('Everything is going fine!');
});
You are using a mix of jQuery and standalone javascript. You might as well go all the way to jQuery, with something like:
$('#product_grid_list figure:first img').click(function(e) {
alert('Everything is going fine, hopefully!');
});
You did not send the corresponding HTML, so we cannot test whether the above is correct.
it's just a simple click event in jQuery, no need to use js: http://jsfiddle.net/wP3QQ/11/
$('#product_grid_list').find('figure img').click(function(e){
alert('Everything is going fine!');
e.preventDefault();
});
You want the hover effect, so click event should not be used over here. It should be mouseover.
Working Fiddle
Code Snippet:
$(document).on('mouseover','#product_grid_list figure img',function(e){
alert("now it is working");
});
You are attempting to call on(), a jQuery method, on an HTMLElement (a DOM element). You can't do that, jQuery methods can only be called on jQuery collections. It's easy to get a jQuery collection for the elements you desire:
Use .find() to match the images
There's no need for a for() loop, jQuery's .on() will handle looping for you.
You may also want to prevent the default behaviour of your anchors
$(function () {
var imageCount = $('#product_grid_list').find('figure img');
imageCount.on('click', function (e) {
e.preventDefault()
alert('Everything is going fine!');
})
});
JSFiddle

Cant select ids that I loaded with jQuery

I understand that you need to use ".on" to use code that you loaded with jquery after the page has loaded. (At least I think it works that way)
So I tried that but it somehow just doesn't do a thing at all. No errors in the console either.
$("#forgot_password").click(function(){
var forgot_password = '<div id="toLogin" style="cursor:pointer;">Prijava</div>'
$("#loginPopupForm").html(forgot_password);
});
$("#toLogin").on("click", function(){
alert("Hello");
});
So when I click on #forgot_password it does execute the first click function. But when I click on #toLogin it doesn't do anything and I think its because its loaded with jquery when I click on #forgot_password
Try this
$("#loginPopupForm").on("click", "#toLogin", function(){
alert("Hello");
});
You need to bind to an element that is present when the page loads, like body for example. Just change your code to what is shown below
$("body").on("click", "#forgot_password", function(){
var forgot_password = '<div id="toLogin" style="cursor:pointer;">Prijava</div>'
$("#loginPopupForm").html(forgot_password);
});
$("body").on("click", "#toLogin", function(){
alert("Hello");
});
You are setting the on to the wrong thing. You want it to be:
$(document).on('click', '#toLogin', function() {alert('hello') });
The id isn't there until you do the other click event, so jQuery is not finding any element to set the click event on. You need to have an element that has been rendered in the DOM to set the event on.
You are totally right about the problem : on() targets only elements that are already existing as it runs.
What you need in jQuery is called Delegated event and is well explained on the Jquery doc page.
The difference in the code is thin, but it's how you're supposed to do.
You have to specify the parent element
$("#toLogin").on("click","#loginPopupForm", function(){
alert("Hello");
});
in the 2nd argument of the on

Why i can not trigger the jquery function?

This is a button to close the click but it fail and not work. I would like to know what is the tab ID since i did not think i assign one when i create a tab.
Thank you.
This is my attempt
js
$("#closeTab").click(function() {
window.parent.$('#tt').tabs('close','Create List');
});
html
<input type="button" id="closeTab" value="Cancel" class="submit"/>
I found my js code is working but the button can not trigger it? Why? thank you
latest try:
<script>
$(document).ready(function(){
$("#addlist").validate();
});
$(function(){
$("#closeTab").click(function() {
window.parent.$('#tt').tabs('close','Create List');
});
});
</script>
It still doesn't work so i think it is because the upper function ? How to fix this?
================================================================================
Also, are there any ways to clear my session in using this jquery function (what should i add for instance)?**Thanks
With javascript, you have to delay the execution of certain functions (like event handlers) until the page loads fully. Otherwise, it is attempting to bind a function to an element that doesn't yet exist. With jQuery, you can pass a function to jQuery to be executed on page load very easily like this:
$(function(){ /* code goes here */ });
So to use this with your code, you would do this:
$(function(){
$("#closeTab").click(function() {
window.parent.$('#tt').tabs('close','Create List');
});
});
This way, when the jQuery attempts to bind the function to #closeTab, it happens after the page has loaded (and after #closeTab exists).
Do you have any errors in the console?
Do you include jQuery before that click binding?
Try changing the window.parent.... to alert('clicked!'); and make sure you're actually getting there.
Also, make sure the click binding is inside of a:
$(document).ready(function(){
// here
});
A script can close only the windows it creates. It cannot close the tab which it didn't create.
To rephrase, cannot close tab only if unless but when created tab by script which is same that close window.
I hope this makes sense.
Maybe the form is submitted and the browser navigates to another URL before the code could run? Try replacing function() with function(e) and adding e.preventDefault(); to the beginning of the event handler.

jQuery Class selector not working

I'm struggling to make an alert come up when an anchor tag with a specific class is clicked inside of a div.
My html section in question looks like this...
<div id="foo">
<a class='bar' href='#'>Next</a>
</div>
The jQuery section is as follows..
$('.bar').click(function()
{
alert("CLICKED");
});
My problem is that I cannot get this alert to come up, I think that I'm properly selecting the class "next", but it won't pick it up for some reason. I've also tried almost everything on this page but nothing is working. If I don't try to specify the anchor tag i.e. $('#foo').click(function()... then it works, but there will be multiple anchor tags within this div, so simply having the alert executed when the div is clicked won't work for what I need. The website this is on is a search engine using ajax to send information to do_search.php. Within the do_search.php I make pagination decisions based on how many results are found, and if applicable, a next, previous, last, and first link may be made and echoed.
EDIT: I just figured it out, it was my placement of the .next function, since it wasn't created on the initial document load but instead after a result had been returned, I moved the .next function to the success part of the ajax function since that is where the buttons will be created if they need to be, now it works.
Try using the live() command:
$(".bar").live("click", function(){ alert(); });
Because you load your button via AJAX, the click event isn't binded to it. If you use the live() command, it will automatically bind events to all elements created after the page has loaded.
More details, here
.live is now deprecated and is the selected answer for this. The answer is in the comments in the selected answer above. Here is the solution that resolved it for me:
$(document).on('click','.bar', function() { alert(); });
Thanks to #Blazemonger for the fix.
You surely missed $(document).ready(). Your code should be:
$(document).ready(function(){
$('.bar').click(function()
{
alert("CLICKED");
});
});
Hope this helps. Cheers
Make sure you have included JQuery Library properly.
Make sure your script has written between $(document).ready() in short $(function(){ });
Demo : http://jsfiddle.net/W9PXG/1/
<div id="foo">
<a class='bar' href='#'>Next</a>
</div>
$(function(){
$('a.bar').click(function()
{
alert("CLICKED");
});
});

Categories

Resources