JavaScript alert callback not working inside a function - javascript

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

Related

JQuery click() event listener not working

im trying to get a lil project going but im stuck on a very annoying thing.
$(document).ready(function() {
$("#search-button").click(console.log('hello'))
});
as you can see im targeting a search button with the id search-button and as soon as i click it something should happen. in this case i put a console.log in to test if it works but it doesn't. it always logs it as soon as i load the page , not when i click the button i target. ... what am i doing wrong
if you need more info on this pls tell me i tried to keep it as simple as i could
ty for your help
O.k
The click handler needs a function argument, not just the console.log by itself. Try this:
$(document).ready(function() {
$("#search-button").click(function() {
console.log('hello');
});
});
Inside of .click should be a handler .click(handler) and the handler should be a function. The browser is reading the code and when it hits console.log('hello'), it does it! It's seeing .click etc, but it doesn't matter; it next sees console.log and does it.
Try
$(document).ready(function() {
$("#search-button").click(function() {
console.log('hello');
});
});
As others have mentioned, the click function requires its own callback function. You can also use this, without requiring the use of document:
$("#search-button").on('click', function() {
console.log('hello')
})
I hope You're using jQuery version 3 or up. if you use 3 or up jquery version the good practice is you use Document binding Example:
jQuery(document).on('click', '#search-button', function(event) {
//your Code here...
console.log('hello');
});

Capturing and bubbling events

I created the next jsfiddle:
http://jsfiddle.net/AHyN5/6/
This is my code:
var mainDiv = document.getElementsByClassName('mainDiv');
var div = mainDiv[0].getElementsByClassName('data');
mainDiv[0].addEventListener("click", function(e) {
alert('1');
});
$(mainDiv[0]).children('img').click(function (e) {
e.stopImmediatePropagation()
return false;
})
I want that click on the pink background will popup a message with value of 1(an alert message).
When clicking the yellow, I want nothing to happen.
I read this blog but with no success..
Any help appreciated!
I agree with the others stating to use jQuery or straight DOM calls.
Here is another shot at the jQuery solution - very similar to the one above. I went ahead and presented it because it targets the images directly - in case that's what you're really trying to accomplish.
$(function()
{ var mainDiv = $('div.pink:first'),
imgs = $('img');
mainDiv.click(function()
{ alert('1');
});
imgs.click(function(e)
{ e.stopImmediatePropagation();
});
});
You could add pointer-events: none; to the yellow class. That will cause those elements to not fire click events.
See here for more info https://developer.mozilla.org/en-US/docs/Web/CSS/pointer-events
You have a mix of jQuery and DOM methods calls. Note also that for attaching event listeners, you should wait for all HTML document to be ready.
I'd recommend using either DOM methods ot jquery methods. Following is an example of jquery:
$(function(){
$('.pink:first').on("click", function(e) {
alert('1');
});
$('.yellow').on('click', function (e) {
e.stopPropagation();
});
})
See also this 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

jQuery click() not working on replaced html

I am trying to create a go-moku game using jquery,php, and mysql database.
I have a ajax function that updates the a board every second if needed.
var turnCount = -1;
setInterval(function(){
$.get('includes/boardControl.php',{turn: turnCount }, function(data){
if(data != "")
{ $("#board").html(data);
turnCount = $("#turnCount").text();
$("#turnCount").text("")
}
});
}, 1000);
This works just fine, it checks the database to see if turn has been incremented and replaces the board if it has. Now what I want to ultimately do is create a click function that use Ajax to update the board and turn count in the database. I am hoping to somehow use the N'th selector do determine what square I'm clicking on.
I have several questions.
1) My click function right now is
$(document).ready(function() {
$("td > img").click(function(){
alert("clicked");
});
});
as of right now it works on a extra test table I wrote into the html, but not on the table created with the previous function. What am I doing wrong?
2) The tutorials I've looked at so far dictate that I should write code in the following way.
$(document).ready(function() {
//code here
});
When i asked a question last night, I was told that I was over complicating things with my functions. So when should i use a document.ready function and when not? And is it fine to put all of my scripts into one document.ready function or should I have multiple?
3)
Once I get the click image to work I am hoping to send a X,Y coordinate to the server and change that corresponding spot on the board. How would I determine what cell in the table is clicked in order to know what coordinates to use? (or is there a much easier way?)
sounds like you need to change
$("td > img").click(function(){
alert("clicked");
});
to
$("td > img").live('click',function(){
alert("clicked");
});
Edit: For jQuery 1.9 and later you can do:
$("#board").on('click', 'td > img', function(){
// handle click
});
The $(document).ready() function only fires when the page first loads - in order to make this work try something like this:
function bindClicks() {
$("td > img").click(function(){
alert("clicked");
});
}
$(document).ready(bindClicks);
This will allow you to call bindClicks() later on if need be to bind the click events of a new table.
1) Are you re-wiring the click event after the ajax content loads?
The $(document).ready function will fire as soon as the page is fully loaded, but won't fire after ajax calls. So you will need to re-wire the click event after every ajax call:
2) KISS. Keep it as simple as possible. If you have 50+ lines inside a document.ready statement you might want to create some functions.
3) The best way to accomplish this might be to assign a specific ID to each cell and capture that in the click event. You can then pass that to the server and update the specific cell on the return.
Are you sure JQuery is matching you query:
$("td > img")
I would load firefox with firebug and check that your actually getting match first. The second table your creating may have a slightly different structure then you expected and firebug can show you the exact structure also.
Goodluck.

Javascript + jQuery, click handler returning false to stop browser from following link

I'm trying to stop the browser from following certain links, rather I want to unhide some Divs when they are clicked.
I'm having trouble just getting the links to not be followed though.
Here's what I have:
var titles = $('a.highlight');
jquery.each(titles, function(){
this.click(function(){
return false;
});
});
It seems like the click handler is not being assigned. What am I missing?
Try
this.click(function(e){ e.preventDefault(); }
Actually, it looks like you might need to use the jQuery constructor on this:
$(this).click(function(){ return false; }
You could also try using parameters on the each function instead of using this:
jQuery.each( titles, function(index, elem) { $(elem).click( function() { return false; } ) } );
Personally, I would just do titles.each( ... though. In that instance you can use this to bind the click handler. I am not sure off the top of my head what this binds to with jQuery.each
Or just calling click on titles:
titles.click( function() { return false; } )
That will bind click to every element in titles. You don't need to loop through them.
You can compress that jquery a bit:
$('a.highlight').click(function() { return false; });
You should also make sure that:
There are no other click handlers registered for those elements later on.
The code you have is attaching after the elements have loaded. If they're not completely loaded, they won't be found in the $('a.highlight') selector. The easiest way to do this is to put your code in a $(document).ready(function() { *** code here *** }); block.
Edit: As per other responses - the problem was that this represents a DOM object, while $(this) is a jquery object. To use the .click function to attach a handler, you need a jquery object.
In short, using this inside the each loop won't work with what you're trying to do. You'll need to get a jquery representation by using $(this) instead.

Categories

Resources