unable to attach click event to li element using jquery - html

I am unable to get the click event for this HTML:
<ul id="frd_overlay_list">
<li><div class="divLink"><div id="1"><img src="path"><div class="frdName">Name</div></div></div></li>
<li><div class="divLink"><div id="2"><img src="path"><div class="frdName">Name</div></div></div></li>
</ul>
and JQuery script:
$('li').click(function(){
console.log('Not working');
});
I am able to get click event for the ul element i.e.
$('ul#frd_overlay_list').click(function(){
console.log('This works');
});
I have tried this, but this also doesnt work:
$('ul#frd_overlay_list li').click(function(){
console.log('Doesn't work either');
});
Please give me pointers what am I doing wrong?

All your example works except for the last one:
You need to escape the ' or use double quotes for the string
$('ul#frd_overlay_list li').click(function(){
console.log("Doesn't work either");
});
Since you want to apply the click events for dynamically added elements, you could use on function of jQuery.
on would bind event handlers for dynamically added elements
bind would only bind event handlers for currently existing elements.
Usage of on:
$("ul#frd_overlay_list li").on("click", function(){
console.log("Doesn't work either");
});
Fiddle

Related

jquery on() method doesnt work with td child? [duplicate]

I have the following markup
<ol>
<li class="ListItem">
<span class="sub">#qItem.CategoryText</span>
<input type="image" src="http://icons.iconarchive.com/icons/tatice/just-bins/256/bin-red-full-icon.png" width="30" class="deleteIcon" name="QuestionId" value="#qItem.Id" />
</li>
</ol>
and the following script
$(".ListItem").click(function(){
doActionA();
});
$(".deleteIcon").click(function(){
doActionB();
});
When I click in image, it also triggers click of ListItem. I understand this is because image is inside ListItem. but I want ListItem's click not to be fired when image is clicked.
Is there any way to do that ?
$(".deleteIcon").click(function(e){
doActionB();
e.stopPropagation();
});
You need to use event.stopPropagation() to prevents the event from bubbling up the DOM tree.
$(".deleteIcon").click(function(event){
event.stopPropagation()
doActionA();
});
The event you binded with delete icon is firing the parent event binding with ListItem, so you need to stop propagation for parent event when child is source of event.
$(document).on("click", ".deleteIcon", function() {
doActionB();
});
This method is the only one I found to work with nested elements, especially those generated by a library such as Pivottable (https://github.com/nicolaskruchten/pivottable)
$(".deleteIcon").click(function(){
doActionA();
return false;
});
Use .one(), as directed in the JQuery documentation.

How to disable and then re-enable onclick event in <img> using jquery

I have used an image instead of button, now I want to disable the onclick() event in some case as we disable a button. I tried many ways but doesn't work. Below is what I did:
<img title="Ok" class="mtbtn"id="upd_1" onclick="add_edited('1','MM');" src="/project/images/green_ok.gif" border="0">
The jQuery code is:
$("#upd_1").css('opacity','0.5');
$("#upd_1").unbind("click");
I also tried:
$("#upd_1").css('pointer-events','none'); and document.getElementById('upd_1').style.pointerEvents = 'none';.
Any solution?
Try this:
$("#upd_1").on('click',function(e){
e.preventDefault();
});
One hint is that you can give your click event a suffix so you can be sure it's the only event you are affecting. To bind:
$('#elementId').on('click.myevent', function () {
// your code
}
To unbind:
$('#elementId').off('click.myevent');
Not going into binding or unbinding the click event but how about creating a mask for the image. Hide the mask when you want the image to be clickable else show it.
img onclick="alert('clicked')" src="http://lh3.googleusercontent.com/mjejVTJKT4ABNKq2HGlkDs36f-QvzI2hKFER098vBIgiAoZ2H-SN5QPvFaZEVDZRxfujrS6pszZ_J-_di2F57w0IFE3KAciDwGAh-9RcCA=s660" alt="" />
<div id="mask"></div>
<script>
$('#mask').hide();
$('#disable').click(function() {
$('#mask').show();
});
$('#enable').click(function() {
$('#mask').hide();
});
</script>
Try the Plnkr: Plnkr
Try this way. Add your parameters in two attributes (data-a and data-b for example).
<img title="Ok" class="mtbtn"id="upd_1" data-a="1" data-b="MM" src="/project/images/green_ok.gif" border="0">
Then change your javascript in this way:
$(document).ready(function(){
$("#upd_1").bind("click", function(){
var a = $(this).data("a");
var b = $(this).data("b");
// Code here
$(this).unbind("click");
});
});
Here the result.
Alternative is this:
var semaphore = true;
function add_edited (a, b) {
if (semaphore) {
semaphore = false;
// Code here
}
}
Create a semaphore to manage the execution of the code to the click.
i understood you'r problem, there is no need to unbind() and re bind() the onclick event, you can simply remove and re-add onclick attribute using removeAttr() and attr()
<img title="Ok" class="mtbtn"id="upd_1" onclick="add_edited('1','MM');" src="/project/images/green_ok.gif" border="0">
JQuery:
$("#upd_1").css('opacity','0.5');
$("#upd_1").removeAttr('onclick');
to re add onclick event do the following:
$("#upd_1").css('opacity','1');
$("#upd_1").attr("onclick","add_edited('1','MM');");
that is all you need to do.

HTML onclick attribute with variable URL

Below code is for navigating to the Google Webpage when the element <li> is clicked.
<li onclick="window.location='http://www.google.com';" style="cursor:pointer;">Google</li>
Now I have another <li> which goes to different websites depending on a parameter. I tried this
<script>
document.write('<li onclick="window.location='http://www.google.com/mmm/yyy/' + random_variable + 'ddd/eee';" style="cursor:pointer;">Google</li>');
</script>
This isn't working fine. What am I doing wrong?
You don't want to use document.write. Instead you can change the attributes of the tags themselves. onClick is just javascript inside your code so you can replace variables
<li onclick="location.href='http://www.google.com/mmm/yyy/' + random_variable + 'ddd/eee';">Google</li>
It's a little messy. I'd personally do it with jQuery and a regular <a> tag
Javascript/jQuery
$(document).ready(function() {
$('#someid').click(function(e) {
e.preventDefault()
location.href= 'http://google.com/' + random_variable;
});
});
Or if your random variable is available onload you could just replace the href attribute
$(document).ready(function() {
$('#someid').attr('href','http://google.com/' + random_variable);
});
HTML
<li>Google</li>
var targetElement = document.getElementById("id");
targetElement.appendChild('<li>...</li>';
The first line find the existing element, where you want to insert the <li>.
The second line insert it.

Hover not working on AJAX

I have the below content that loads on through AJAX.
<div class="grid">
<div class="thumb">
<img alt="AlbumIcon" src="some-image.jpg">
<div style="bottom:-75px;" class="meta">
<p class="title">Title</p>
<p class="genre"> <i class="icon-film icon-white"></i>
Genre
</p>
</div>
</div>
</div>
Additionally, I have writen the following script in jquery that applies to the above 'div.grid'.
jQuery(function ($) {
$(document).ready(function () {
$(".grid").on({
mouseenter : function () {
$(this).find('.meta').stop().animate({
bottom:'0px'
},200);
},
mouseleave : function () {
$(this).find('.meta').stop().animate({
bottom:'-75px'
},200);
}
});
});
});
The script works fine when the page loads the first time. However, the hover effect doesn't work once the above div is generated via AJAX after clicking on an 'a' tag. I can't seem to figure out what's wrong here? New to all this. Can anyone help?
To append these event handlers to dynamically generated elements, you need to bind to the document or another static parent element and then specify .grid as the second argument passed to .on.
The second argument is used as a filter to determine the selected elements that trigger the event. So when the event is fired it will propagate to the document or parent element selected by jquery. The event target will then be scrutinized using the selector provided as the second argument. If the target matches the second argument, (.grid in our case), the event is fired.
You can read more in the jQuery documentation.
Also, since your using document.ready there is no need for the short hand ready statement, jquery(function($).
$(document).ready(function () {
$(document).on({
mouseenter : function () {
$(this).find('.meta').stop().animate({
bottom:'0px'
},200);
},
mouseleave : function () {
$(this).find('.meta').stop().animate({
bottom:'-75px'
},200);
}
}, ".grid");
});
you lost your binding because of ajax that overwrite your div with class=".grid"
use parent element for binding
$('.ParentElementClass').on("mouseleave", ".grid", function(){...})
more from jquery api
Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time. By picking an element that is guaranteed to be present at the time the delegated event handler is attached, you can use delegated events to avoid the need to frequently attach and remove event handlers. This element could be the container element of a view in a Model-View-Controller design, for example, or document if the event handler wants to monitor all bubbling events in the document. The document element is available in the head of the document before loading any other HTML, so it is safe to attach events there without waiting for the document to be ready.
Not sure what you're shooting for here but a little malformed HTML may have done it...
jsFiddle Demo
<div class="grid">
<div class="thumb">
<img alt="AlbumIcon" src="some-image.jpg" />
<div style="bottom:-75px;" class="meta">
<p class="title">Title</p>
<p class="genre"><i class="icon-film icon-white"></i>Genre</p>
</div>
</div>
</div>
$(function () {
$(".grid").on({
mouseenter: function () {
alert('entered');
$(this).find('.meta').stop().animate({
bottom: '0px'
}, 200);
},
mouseleave: function () {
alert('left');
$(this).find('.meta').stop().animate({
bottom: '-75px'
}, 200);
}
}, ".thumb");
});
});
Be sure to close img tags. They're notorious for causing intermittent glitches.
You can just use the hover function:
jQuery(function ($) {
$(document).ready(function () {
$(".grid").hover(function () { /*mouseenter*/
$(this).find('.meta').stop().animate({
bottom:'0px'
},200);
},function(){ /*mouseleave*/
$(this).find('.meta').stop().animate({
bottom:'-75px'
},200);
}
});
});
Explanation:
The first parameter function does the work of mouseenter and the second does the work of mouseleave.
I'd recommend using those both, mouseenter and mouseleave in situation when you don't want an effect back when the user gets off his mouse from the element.

Prevent page from going to the top when clicking a link

How can I prevent the page from "jumping up" each time I click a link? E.g I have a link somewhere in the middle of the page and when I click it the page jumps up to the top.
Is the anchor href="#"? You can set it to href="javascript:void(0);" instead.
If you are going to a prevent default please use this one instead:
event.preventDefault ? event.preventDefault() : event.returnValue = false;
Let's presume that this is your HTML for the link:
Some link goes somewhere...
If you're using jQuery, try like this:
$(document).ready(function() {
$('a#some_id').click(function(e) {
e.preventDefault();
return false;
});
});
Demo on: http://jsfiddle.net/V7thw/
If you're not on jQuery drugs, try with this pure DOM JavaScript:
window.onload = function() {
if(document.readyState === 'complete') {
document.getElementById('some_id').onclick = function(e) {
e.preventDefault();
return false;
};
}
};
It will jump to the top if you set the link href property to # since it is looking for an anchor tag. Just leave off the href property and it won't go anywhere but it also won't look like a link anymore (and make sure to handle the click even in javascript or else it really won't be of much use).
The other option is to handle the click in javascript and inside your event handler, cancel the default action and return false.
e.preventDefault();
return false;