javascript event not registered - javascript

I get a strange behaviour. In a web page i import some script and i define some js function.
<script type="text/javascript">
$(function() {
}
</script>
When i click on a button i display a dialog (this block)
I took some info from the server... and insert it in the bookInfoBlock area
Finally i got
<div id="bookDialog" title="book info" style="display:none">
<button type="button" id="addBook1">+</button>
<div id="bookInfoBlock">
<button type="button" id="addBook2">+</button>
</div>
</div>
$('[id^=addBook]').click(function() {
alert("book test");
});
When i click on button with addBook1, i see the alert... but not when i click on addBook2.
It's like this last one don't know the event and javscript

It looks like you're loading addBook2 dynamically via ajax. In that case use event delegation using .on(). If the div bookInfoBlock is static & is present in DOM all the time, use this.
$('#bookInfoBlock').on('click', '[id^=addBook]'), function() {
alert("book test");
});
or if you're not sure about the static parent, use this
$(document.body).on('click', '[id^=addBook]'), function() {
alert("book test");
});
As of jQuery 1.7, the .live() method is deprecated and removed completely in version 1.9. For older versions use .live() instead of on()
$('[id^=addBook]').live('click', function() {
alert("book test");
});

You can use delegate instead of click .
live isn't more used, there is delegate :
$(document).delegate('[id^=addBook]','click', function() {
alert("book test");
});

Related

jQuery .click() not working (debugging)

I am new to jQuery and am making a few .click() functions for my website, but no matter what I try, I can't get them to work.
jquery:
$(document).ready(function(){
$("#underlay-img-container-btns-add").click(function(){$("#underlay-img-container-form-file").click();});
$("#underlay-img-container-btns-submit").click(function(){document.forms['underlay-img-container-form'].submit();$("#underlay-img-container-general_loader").css("display","inline-block");});
$("#underlay-img-container-form-file").change(function(){readURLImg(this);});
$("#underlay-gif-container-btns-add").click(function(){$("#underlay-gif-container-form-file").click();});
$("#underlay-gif-container-btns-submit").click(function(){document.forms['underlay-gif-container-form'].submit();$("#underlay-gif-container-general_loader").css("display","inline-block");});
$("#underlay-gif-container-form-file").change(function(){readURLImg(this);});
});
readURLImg (displays an image preview before submission. This is part of a file uploading script.):
function readURLImg(input){if(input.files&&input.files[0]){var reader=new FileReader();reader.onload=function(e){$("#underlay-img-container-preview").attr("style","background-image:url("+e.target.result+");color:#fafafa");}
reader.readAsDataURL(input.files[0]);}}
I am sure my ids are correct. I have been trying to find the answer for hours with no success.
i have checked your website
then I've clicked on button upload you picture > opened the terminal and test
$("#underlay-img-container-btns-add").click(function(){alert('btn clicked')})
and the results appears
So, your problem is to call the events when the popups are ready
to Understand the concept
close the popup and try the same code it will retrieve empty array '[]'
<div class="btn" id="green" >
<div class="icon-image"></div>
<span>Upload your picture</span>
</div>
and add
$('.btn#green').click(function() {
$('.overlay').html($('.overlay').html().replace(/!non_select_tag!/g, 'img'));
$('.overlay').html($('.overlay').html().replace(/!non_select_txt!/g, 'Picture'));
// add you events
$("#underlay-img-container-btns-add").click(function(){alert('btn clicked')})
$('.overlay').show();
})
this will work
try
$("#underlay-img-container-btns-add").on( 'click', function () { ... });
may not work because content is dynamically created.
try
$("#underlay-img-container-btns-add").bind( 'click', function () { ... });
To bind events to dynamically generated elements in DOM, you may use
$('document').on( 'click', '#selector', function () {
...
});
This binds event to the DOM rather than to the element directly, which may not exist all the time.
try
$("body").delegate("#underlay-img-container-btns-add",'click',function(){
....
});

Added Div not working click function

In my scenario , i have to use class to add div , this may easily solve with onClick function, but i require this to complete my task,
.click(function() is not working on new element , javascript /jquery may store element onload or what???
FIDDLE
<div class="add">
<div class="anyRow">Hello<hr/></div>
</div>
$('.anyRow').click(function(){
$('.add').append('<div class="anyRow">Hello</hr></div>')
});
You have to use on() method as the deprecated live() one, to delegate click for future new elements.
$(document).on("click", ".anyRow", function() {
$('.add').append('<div class="anyRow">Hello</hr></div>');
});
If you are using in real case (as in posted jsFiddle) jQuery v1.6.4, you should use .delegate() method:
$('.add').delegate('.anyRow', 'click', function () {
$('.add').append('<div class="anyRow">Hello</hr></div>')
});
-DEMO-
http://learn.jquery.com/events/event-delegation/
For older jquery versions you can use live function if html is changed dynamically (I saw you using an older jquery version in the fiddle)
$('.add').live( 'click', function () {
$('.add').append('<div class="anyRow">Hello</hr></div>')
});
The method bellow applies event handlers to elements even before they exist
$("#parent-element").on("click", "#new-element", function() {
// your code
});

Not working Jquery

I using comboBox Plugin.When i choose zawgyi-one in dropdown listbox, jquery not working.Why?
html
<div class="result">
<span>မြန်မာစာ(Myanmar Text)</span>
</div>
<!-- For Testing Jquery -->
<button id="click-btn">Jquery Testing Button</button>
javascript
jQuery(function($){
$(document).ready(function(){
$("#click-btn").click(function (){
alert("jquery Work");
});
});
});
DMEO LINK is http://jsfiddle.net/qq6uq7c6/11/
I have found the issue.
The combobox plugin is calling this line document.body.innerHTML=_html; when ever a select change is happening. What that does is replace the elements with clone of same elements but the problem here is it doesn't clone the events attached to it. (So i recommend not to use this plugin itself since it may kill other plugin events also).
To over come this you can use jQuery delegated event and it HAS TO BE assigned to document object or any parent object and use jQuery instead of $.
The updated code will look like
jQuery(document).ready(function(){
jQuery(document).on('click',"#click-btn",function (){
alert("jquery Work");
});
});
Here is a working fiddle.

Access dynamically created items using jQuery?

I have a page where some html is being dynamically added to the page.
This is the html and javascript that is created:
<div>
<script type="text/javascript" language="javascript">
$('#btn').click(function() {
alert("Hello");
});
</script>
<a id="btn">Button</a>
</div>
Looking in my Firebug console, I get an error that says:
TypeError: $("#btn") is null
jQuery is being loaded on the page initially.
What am I doing wrong here?
You have to bind on() (or the events defined within the on() method, to an element that exists in the DOM at the point at which the jQuery was run. Usually this is on $(document).ready() or similar.
Bind to the closest element in which the $('#btn') element will be appended that exists in the DOM on page-load/DOM ready.
Assuming that you're loading the $('#btn') into the #container div (for example), to give:
<div id="container">
<div>
Button text
</div>
</div>
Then use:
$('#container').on('click', '#btn', function(){
alert('Button clicked!');
});
Use .on to wire up the event to your button. Check this SO answer:
Event binding on dynamically created elements?
$(document).ready(function() {
$('body').on('click', '#btn', function() {
alert("Hello");
});
})
Edit: I added the document ready code, you'll want to make sure you do that.
Fixed.
you are looking for .on here which will bind the click event to dynamically added nodes.
$("#parent_container").on("click", "#btn", function () {
alert("hello")
})
the docs: http://api.jquery.com/on/
Try
<div>
<a id="btn">Button</a>
</div>
<script>
$('#btn').on('click', function() {
alert("Hello");
});
</script>
The problem in your code is that you are attaching the event to the button before the button is being created.
Correct version is:
<div>
<a id="btn">Button</a>
<script type="text/javascript" language="javascript">
$('#btn').click(function() {
alert("Hello");
});
</script>
</div>
This should do the job.
Use the .live() function of jQuery

jQuery function not binding to newly added dom elements

Here's index.html:
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('.btn_test').click(function() { alert('test'); });
});
function add(){
$('body').append('<a href=\'javascript:;\' class=\'btn_test\'>test</a>');
}
</script>
</head>
<body>
test1
add
</body>
If I click on test1 link, it shows alert('test'), but if I click on add link then click on test, it doesn't show anything.
Could you explain it?
For users coming to this question after 2011, there is a new proper way to do this:
$(document).on('click', '.btn_test', function() { alert('test'); });
This is as of jQuery 1.7.
For more information, see Direct and delegated events
You need to use a "live" click listener because initially only the single element will exist.
$('.btn_test').live("click", function() {
alert('test');
});
Update: Since live is deprecated, you should use "on()":
$(".btn_test").on("click", function(){
alert("test");
});
http://api.jquery.com/on/
I have same problem like question I was just near to pulling my hair then i got the solution.
I was using different syntax
$(".innerImage").on("click", function(){
alert("test");
});
it was not working for me (innerImage is dynamically created dom)
Now I'm using
$(document).on('click', '.innerImage', function() { alert('test'); });
http://jsfiddle.net/SDJEp/2/
thanks #Moshe Katz
.click binds to what is presently visible to jQuery. You need to use .live:
$('.btn_test').live('click', function() { alert('test'); });
Use Jquery live instead. Here is the help page for it http://api.jquery.com/live/
$('.btn_test').live(function() { alert('test'); });
Edit: live() is deprecated and you should use on() instead.
$(".btn_test").on("click", function(){
alert("test");
});
This is because you click event is only bound to the existing element at the time of binding. You need to use live or delegate which will bind the event to existing and future elements on the page.
$('.btn_test').live("click", function() { alert('test'); });
Jquery Live
you need live listener instead of click:
$('.btn_test').live('click', function() {
alert('test');
});
The reason being is that the click only assigns the listener to elements when the page is loading. Any new elements added will not have this listener on them. Live adds the click listener to element when the page loads and when they are added afterwards
When the document loads you add event listeners to each matching class to listen for the click event on those elements. The same listener is not automatically added to elements that you add to the Dom later.
Because the event is tied to each matching element in the document ready. Any new elements added do NOT automatically have the same events tied to them.
You will have to manually bind the event to any new element, after it is added, or use the live listener.
$('.btn_test').click
will add the handler for elements which are available on the page (at this point 'test' does not exist!)
you have to either manually add a click handler for this element when you do append, or use a live event handler which will work for every element even if you create it later..
$('.btn_test').live(function() { alert('test'); });
After jquery 1.7 on method can be used and it really works nice
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js">
</script>
<script>
$(document).ready(function(){
$("p").on("click",function(){
alert("The paragraph was clicked.");
$("body").append("<p id='new'>Now click on this paragraph</p>");
});
$(document).on("click","#new",function(){
alert("On really works.");
});
});
</script>
</head>
<body>
<p>Click this paragraph.</p>
</body>
</html>
see it in action
http://jsfiddle.net/rahulchaturvedie/CzR6n/
Or just run the script at the end of your page
You need to add a proper button click function to give a proper result
$("#btn1").live(function() { alert("test"); });

Categories

Resources