alert not being fired when I append a new div - javascript

On this fiddle http://jsfiddle.net/adrianjsfiddlenetuser/zyUkd/46/ the divs 'Hello 01' & 'Hello 02' fire an alert when they are clicked. When i click 'Add New' a new div is added but when I click on this div the alert is not fired even though it is styled with same css .
How can I amend this so that the alert is fired when a new div is appended ?
Code from jsFiddle for posterity
JS
$(function() {
$(".myDivs").click(function() {
alert('Clicked');
});
$("#button").click(get);
function get() {
$(".connected").append("<div class=\"myDivs\">hello</div>");
}
});
HTML
<div class="connected">
<div class="myDivs">Hello 01</div>
<div class="myDivs">Hello 02</div>
</div>
<input name="Button3" type="button" value="Add New" id="button">
​
​

You need delegate event handler, because your way on bind event only bind event to existing DOM .myDivs, but not for upcoming.
$(".connected").on('click', '.myDivs', function() {
alert('Clicked');
});
DEMO
For more detail go here

That's because your jQuery is using the document.ready to make the assignment. Because this element was not present at the load, it does not have this assignment. You need to make this assignment separately.

the answer thecodeparadox gave is valid. But I went ahead and updated your fiddle to fully match the latest jQuery convention.
DEMO
Here's a link to the jQuery documentation for more information:
jQuery .on()

Related

Sortover and sortout events not triggered after element is replaced

The middle column should change width when dragging element over it. It does work until I click on replace button which replaces the html of the middle column. Then the events stop being triggered. As far as I know .on() should be able to handle such cases, or am I wrong?
This is a simple demo which demonstrates the issue: https://jsfiddle.net/shuetvyj/3/
HTML:
<div class="members-column">
<div class="sort"> 1 </div>
<div class="sort"> 1 </div>
</div>
<div id="groupB" class="members-column">
</div>
<div class="members-column">
<div class="sort"> 2 </div>
</div>
replace groupB
Javascript:
$(".members-column").sortable({
items: ".sort",
connectWith: ".members-column"
});
$("#groupB").on("sortover", function() {
console.log('overB');
$('#groupB').css('min-width','80px');
});
$("#groupB").on("sortout", function() {
console.log('outB');
$('#groupB').css('min-width','');
});
$("#replace").on("click", function(e) {
e.preventDefault();
$("#groupB").replaceWith('<div id="groupB" class="members-column"></div>');
});
Instead using replaceWith use .html as below
$("#replace").on("click", function(e) {
e.preventDefault();
$("#groupB").html("");
});
https://jsfiddle.net/shuetvyj/5/
Using replaceWith
$('body').on('sortover', '.members-column', function() {
$('#groupB').css('min-width','80px');
});
$('body').on('sortout', '.members-column', function() {
$('#groupB').css('min-width','');
});
$("#replace").on("click", function(e) {
e.preventDefault();
$("#groupB").replaceWith('<div id="groupB" class="members-column"></div>');
$(".members-column").sortable({ items: ".sort",connectWith: ".members-column" });;
});
https://jsfiddle.net/shuetvyj/8/
when you replace the html, the listeners you had attached to the old html are not reattached to the new html.
As a result, your handlers will no longer get called.
To solve this, simply attach the listeners to the new html when you have replaced it.
(jQuery solved this for a while with live instead of on, which would automatically attach listeners after dom changes) http://api.jquery.com/live/
But live() has been deprecated since jQuery 1.7 and was removed in 1.9
additionally, removing the column probably also breaks sortable's behavior (since it does not store the selector but the result of the selector when it was first called, and thus retains a reference to the div you removed from the DOM.
In short ; do not remove the column div once you have sortable listening to it, just clear or replace its contents

Jquery Click not working in IBM Mobile first

Below is the code i have added in main.js file
$(function(){
$(".menuHorizontal div").click(function(){
console.log('hi');
});
});
Below is my html DOM structure
<div class="menuHorizontal">
<div class="yellow-borBottom">All</div>
<div>Elevators</div>
<div>Escalators</div>
<div>Walkways</div>
</div>
my jquery click function wont works, no event on click. not even it shows error in console. plz help me to resolve this
I have added a seperate Jquery file too but still wont works
The way that you have this scoped attaches an event to all div's contained within a div assigned class menuHorizontal. In the code that you posted, there are none of these!
<div class="menuHorizontal">mush be close with</div> // No divs inside here!
You closed the div with class menuHorizontal too soon. Two options below. The former will also attach the event to the "mush be close with" text, while the latter will not.
<div class="menuHorizontal">
<div>mush be close with</div>
<div class="yellow-borBottom">All</div>
<div>Elevators</div>
<div>Escalators</div>
<div>Walkways</div>
</div>
<div class="menuHorizontal">>mush be close with
<div class="yellow-borBottom">All</div>
<div>Elevators</div>
<div>Escalators</div>
<div>Walkways</div>
</div>
Were you trying to scope like this, which attaches the event to div's with class menuHorizontal?
$("div.menuHorizontal").click(function(){
console.log('hi');
You might also want to change your scope to the higher level div, like so. Google event bubbling for more info
$(".menuHorizontal").click(function(){
console.log('hi');
Also, consider using jQuery .on(), as follows. It's a little more current, and generally more flexible.
http://api.jquery.com/on/
$(function(){
$(".menuHorizontal div").on('click', function(){
console.log('hi');
});
});
$(".menuHorizontal div").click(function(){
console.log('hi');
});
This does not work because in your HTML <div class="menuHorizontal">mush be close with</div> you dont have a div inside of the div .menuHorizontal so the event is not binded on any div ( as it doesn't exist). So you can do as below.
Change your HTML to
<div class="menuHorizontal">mush be close with
<div class="yellow-borBottom">All</div>
<div>Elevators</div>
<div>Escalators</div>
<div>Walkways</div>
</div>
And the existing jquery must work fine.
And here is Working Fiddle

Why can't I trigger a click event on a hyperlink through code

I am trying to implement a manual click event on a hyper-link using jquery but I am not getting how to do it..
Here is my sample fiddle link [1]: http://jsfiddle.net/akki/XyVDd/1/
<input type="text" class="example" id="opval" value="back">
<a id="sub_name" href="http://www.google.co.in">abc</a>
$(document).ready(function(){
if($('#opval').val() =='back') {
$('#sub_name').click();
//$('#qwe').find('a').trigger('click');
}
$('#sub_name').click(function(){
alert(hi)
});
});
A few minor problems here:
1. You don't have jQuery loaded in your fiddle.
2. You need to have "hi" in quotes in your alert().
The main thing though is that you're triggering the click event before your click handler is attached. Just move the handler code to before the click trigger:
$(document).ready(function(){
$('#sub_name').click(function(){
alert("hi");
});
if($('#opval').val() =='back') {
$('#sub_name').click();
}
});

Prevent icon inside disabled button from triggering click?

Trying to figure out proper way to make a click event not fire on the icon of a disabled link. The problem is when you click the Icon, it triggers the click event. I need the selector to include child objects(I think) so that clicking them triggers the event whenever the link is enabled, but it needs to exclude the children when the parent is disabled.
Links get disabled attribute set dynamically AFTER page load. That's why I'm using .on
Demo here:(New link, forgot to set link to disabled)
http://jsfiddle.net/f5Ytj/9/
<div class="container">
<div class="hero-unit">
<h1>Bootstrap jsFiddle Skeleton</h1>
<p>Fork this fiddle to test your Bootstrap stuff.</p>
<p>
<a class="btn" disabled>
<i class="icon-file"></i>
Test
</a>
</p>
</div>
</diV>​
$('.btn').on('click', ':not([disabled])', function () { alert("test"); });​
Update:
I feel like I'm not using .on right, because it doesn't take the $('.btn') into account, only searching child events. So I find myself doing things like $('someParentElement').on or $('body').on, one being more difficult to maintain because it assumes the elements appear in a certain context(someone moves the link and now the javascript breaks) and the second method I think is inefficient.
Here is a second example that works properly in both enabled/disabled scenarios, but I feel like having to first select the parent element is really bad, because the event will break if someone rearranges the page layout:
http://jsfiddle.net/f5Ytj/32/
Don't use event delegation if you only want to listen for clicks on the .btn element itself:
$('.btn').on('click', function() {
if (!this.hasAttribute("disabled"))
alert("test");
});​
If you'd use event delegation, the button would need to be the matching element:
$(someParent).on('click', '.btn:not([disabled])', function(e) {
alert('test!!');
});​
Demo
Or use a true button, which can really be disabled:
<button class="btn" [disabled]><span class="file-icon" /> Test</button>
Demo, disabled.
Here, no click event will fire at all when disabled, because it's a proper form element instead of a simple anchor. Just use
$('.btn').on('click', function() {
if (!this.disabled) // check actually not needed
this.diabled = true;
var that = this;
// async action:
setTimeout(function() {
that.disabled = false;
}, 1000);
});​
.on('click', ':not([disabled])'
^ This means that, since the icon is a child of the button ".btn", and it is not disabled, the function will execute.
Either disable the icon, also, or apply the event listener only to the <a> tag that is your button, or use e.stopPropagation();
I would suggest using e.stopPropagation();, this should prevent the icon from responding to the click.
That doesn't seem to work for me ^
Disabling the icon, however, does.
I would prefer to add the event using delegation here as you are trying to base the event based on the attributes of the element.
You can add a check condition to see if you want to run the code or not.
$('.container').on('click', '.btn', function() {
if( $(this).attr('disabled') !== 'disabled'){
alert('test!!');
}
});​
Check Fiddle
You're not using the selector properly.
$('.btn').not('[disabled]').on('click', function () {
alert("test");
});​
See it live here.
Edit:
$('.container').on('click', '.btn:not([disabled])', function () {
alert("test");
});​
I think what you need is:
e.stopPropagation();
See: http://api.jquery.com/event.stopPropagation/
Basically something like the following should work
$('.icon-file').on('click', function(event){event.stopPropagation();});
You may want to add some logic to only stop bubbling the event when the button ist disabled.
Update:
not sure, but this selector should work:
$('.btn:disabled .icon-file')

jQuery show not working after added a new element in document

I am loading elements into a div container using Ajax / Request. By default I'm hiding an input box. If a user clicks an edit icon on that div, I want to show the input box. Here is my code:
HTML CODE
<div class='container'>
<input type = 'text' onkeydown='saveFn(event,this)' name = 'editemail' class = 'editemail' style='display:none; height:20px;' />
</div>
JS CODE
$(".container").click(function(){
console.log($(this).find(".editemail").show()); //Note it works fine If i didn't load any new elements into the div.
});
Console Log Output before loading new element into the container.
<input type="text" onkeydown="saveFn(event,this)" name="editemail" class="editemail" style="height: 20px; " value="hyther#zohocorp.com" title="press enter to save">
Console Log Output after loading an element into the container.
<input type="text" onkeydown="saveFn(event,this)" name="editemail" class="editemail" style="height: 20px; display: none; " value="saravanan#zohocorp.com" title="press enter to save">
Even though I am also tried to remove the "style" attribute from this element and adding a new style element, it still doesn't work.
First you should read the jQuery Docs FAQ section: Why_do_my_events_stop_working_after_an_AJAX_request
Use on() to delegate the handler for future elements
$(document).on('click', ".container", function(){
/* your code*/
})
Try this instead:
$(document).on('click','.container',function(){
http://api.jquery.com/on/
Try this one instead:
$('.container').live('click', function(){
/* Your Code Here */
});
The problem is that the click() bound is getting lost after an ajax request. In JQuery you can use .live() function to get this working however this function is now deprecated and they encourage you to use .on() or .delegate(). Personally i've have tons of headecks using .on() and .delegate() and rather use the plugin livequery. With livequery plugin is as simple as:
$(function(){
$('#elementId').livequery('click',function(){
//do something on click
})
});
For more information go to:
.livequery()
.on()
.delegate()

Categories

Resources