i tried to create Jquery function to detect keydown in dynamic added table,
but it wont work :
this is my code
$(document).ready(function(){
$('#create').on('click',function(){
$('#test').append(<table class='dynamic'><tr><td><div class="focus">Name</div></td></tr><tr><td>address</td></tr>)
});
$(document).keydown(function(e){
if($(e.target).closest('table').hasClass('dynamic')&& $(e.target).hasClass('focus'))
{
alert('ok');
};
})
});
and this is my html :
<BODY>
<DIV ID="test"></DIV>
<button id="create">create it!</button>
</BODY>
please help me gusy
I found several errors in your sample. First, is that without input fields any keydown event will be fired on document element and you never will get your condition true. Second, is a code issue. You can't use jQuery functions without wrapping DOM elements into jQuery object. if(e.target.closest('table').hasClass('dynamic')
As example I made a sample fiddle for you. Also I guess you may be interested in such implementation but using mouseover event, which would be better for your case
Related
I want to put text into a textarea input element using key events in jquery. I know that it can be simply done with .val() or .html() functions but there's a reason that I want to put text using keyevents. The following is my code:
<!DOCTYPE html>
<html>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<p>In this example, the text field gets focus immediately after the document window has been loaded.</p>
<textarea id="myText"> </textarea>
<script>
$(function() {
document.getElementById("myText").focus();
$('#myText').focus().trigger({ type : 'keypress', which : 65 });
$('#myText').trigger(jQuery.Event('keypress', { keyCode: 65 }));
});
</script>
</body>
</html>
I have googled it and realized that there is two different ways of triggering events using jquery. I tried both but neither of which seem to be working.
It looks like your keypress event is getting fired, but since it is only an event I don't believe it is actually going to input your value into the field. If you're expecting something to happen on the keypress event from some other code you have, then there is some other issue.
If you demo with this fiddle you'll see the keypress event firing.
Try the code below to change the value of the input field with the new keypress value:
$(function() {
$('#myText').trigger(jQuery.Event('keypress', { keyCode: 65 })).val($("#myText")
.val() + String.fromCharCode(65));
});
The question is answered over there. Being short - key events won't change the actual input due to security reasons, but there is a plugin called "The $.fn.sendkeys Plugin" which can help you with a workaround.
I am currently working in a big web project where we have lots of dom elements which need a listener for click/change/... events. The first 500 lines of code of the main javascript file look like this.
$( ".bla" ).each(function(e) {
$(this).on("click", function(){
...
});
});
So basically we add like 100 listeners and for each listener we have to iterate over the complete dom tree. I think this will take up considerable computation power. Is there something like a best practice solution to avoid this?
You can use event delegation:
$(document).on("click", ".bla", function(){
// ...
});
Hopefully you learned from the other answers that there was no need to use each. However, there may not even be a need to select all elements with class .bla as in your example.
Rather, if a div, or some other element, contains all of the elements for which you are interested in handling a click event, you can put the event listener on the container, and then you determine which element got clicked by inspecting the target property of the event. This works due to 'event propagation' -- if not handled directly handled on the element you clicked, the event will propagate up the DOM.
Simple example below with just two buttons. This is straight Javascript which should easily enough be converted to JQuery -- hope it helps.
<html>
<head>
<script>
setTimeout(function() {
document.getElementById('container').addEventListener('click', function(event) {
alert('You clicked ' + event.target.innerHTML);
});
});
</script>
</head>
<body>
<div id="container">
<button id="fooButton" type="button">foo</button>
<button id="barButton" type="button">bar</button>
</div>
</body>
</html>
I have a problem on my website. I have a <div id="test"> which is display:none by default.
Now, when I click on the button it changes to display:block, but in my div a popup is displayed which disappears when I make a click.
So I need to simulate a click so that the another div does not show.
I tried :
<script>
document.getElementById('test').setAttribute('class','display-block');
document.getElementById('test').click();
</script>
But it does not work.
// element you click to execute the display
$('#button').on('click', function(){
$('#test').css('display','block');
});
Use jQuery .trigger()
http://api.jquery.com/trigger/
$('#test').trigger('click');
document.getElementById('test') returns a plain DOM node which doesn't do much. If you use $('#test') you will get the same DOM node, but wrapped in jQuery.
jQuery provides a .click() function on these "wrapped" nodes, which will simulate a click on the button for you:
$('#test').click();
(which is just a shortcut for .trigger('click') - read more here)
is the same as
$(document.getElementById('test')).click();
You can use jquery to do it:
$('#test').click()
or
$('#test').trigger("click");
Check the demo here: http://jsfiddle.net/eq9c2p2c/
update
You need to add click event, then you just trigger it.
This is the HTML:
<div id="test">click</div>
Javascript:
$('#test').click(function() {
$(this).addClass("border")
})
$('#test').click()
http://jsfiddle.net/eq9c2p2c/2/
I am using jQuery and I have loaded a bunch of JavaScript for a web page which works as expected. However when I try to add the following code to trigger a button click, the button is not activated:
$(document).ready(function(){
$('.add_link').click();
});
I am wondering what I am doing wrong? I have this bit of code in a separate file that gets loaded after all the other JavaScript files are loaded. Any hints?
$('.add_link').click();
Maybe the button is not found, because it does not have the specified class. Look for typos or maybe you just forgot to set the class for the button?
What should happen, when you click the button?
What is the html code for this?
I have found the answer after playing around some more. Since I am using Drupal, I need to use a closure to make sure it works correctly. The correct code should be:
jQuery(document).ready(function($){
$('.add_link').click();
});
It is always the small things that trip you up. Thanks for all the responses.
HTML:
<button class="add_link">Click ME</button>
Javascript:
$(document).ready(function(){
$('.add_link').click(function(event){
//I'm the event handler
console.log(event);
alert(".add_link clicked!!!");
});
});
Other examples:
$(document).ready(function(){
//Named function
function myHandle(event){
//I'm the event handler
console.log(event);
alert(".add_link clicked!!!");
}
//adding event with event alias
$(".add_link").click(myHandle);
//adding event with jQuery.on
$(".add_link").on("click", myHandle);
//adding event with jQuery.on and delegation
$("body").on("click", ".add_link", myHandle);
});
I use jQuery.on because syntax of delegation and simple event handling is almost the same. jQuery.on is newer then jQuery.bind, jQuery.live and jQuery.delegate too.
jsFiddle
I'm using jQuery 1.7.2 with Zoomy and jmpress plugins. Also I'm using boilerplate+bootstrap downloaded from initializr.com
I'm trying to create a "game" like [Waldo/Wally] when you have to find some character in a photo. Each photo has a different character to find.
I'm using jmpress as a presentation plugin to go from one photo to another every time the character is found. jmpress loads the content trough ajax (and I need that behavior) because I want a pretty fast load of the web.
Problem: The .on("click") event is not being caught on one of the elements that exist inside the content loaded.
As an example, I'll explain my problem with one of this characters (just taking parts of code).
I have in my index.html some divs to load the characters, I'll take the nurse character:
<div id="nurse" class="step container" data-src="women/nurse.html" data-x="7500">
Loading...
</div>
The jmpress load the data-src (women/nurse.html) trough ajax when the user is near to that div (step). It loads great.
This is the code of nurse.html
<script type="text/javascript">
new Image().src = "img/nurse_big.jpg";
</script>
<div class="descripcion">
<p>Bla, bla, bla.</p>
</div>
<div class="imagen">
<img src="img/nurse.jpg" alt="Find the nurse" />
</div>
As you can see, I have two divs loaded inside the #nurse div (that has .step class).
I have this code on my js/script.js file when I try to catch the click event:
$(".step").on("click", function(event){
console.log(event.target);
});
I'm also trying with "body" tag to see what happens
$("body").on("click", function(event){
console.log(event.target);
});
If you check the console while the message is showing (div.descripcion) it catch the event and print. But, after the div.descripcion is removed and the image appears, it dosen't. Like if that div.imagen or even elements inside it dosen't exist. The click event is not catched. I tried to catch mousemove event and It does.
Why is not catching the click? any idea?
You can see a working version: [Removed]
And the not working version: [Removed]
UPDATE: I forgot, if I use .on("click") it dosen't work. But if I use .on("mousemove") for example, it works. That's the weird part. .on() is working, but not for the click event.
UPDATE 2: I have removed the links of the live examples because they where dev versions. I'll publish the link to the final work when is published. Thanks to all of you for taking the time. Specially to #Esailija that gives me the answer.
Once again, you need to use on for content loaded later on:
$("body").on("click", ".step", function(event){
console.log(event.target);
});
Replace body with the closest static element that holds the .step elements.
Static means exist in the DOM when the you execute the line:
$(...).on("click", ".step", function(event){
Example:
$('#ContainerId').on("click", ".step", function(event){
// Do what you want.
});
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
on docs
The zoomy plugin you are using does this:
'click': function () {
return false;
}
Since the element you are clicking when you are on the image, is actually the zoomy elements, those get to handle the events first. They handle it by returning false, which means doinge.stopPropagation() as well as e.preventDefault(). So the event won't even come to .imagen.
There is also unterminated multi-line comment in your code, not sure what that does but it can't be good. Consider just deleting code instead of commenting it out.
Anyway, clearing everything like this:
$.cache = {}; //Can also do $("*").off() I think
And then doing:
$(".step").on("click", ".imagen", function(event){
console.log(event.target);
event.preventDefault();
});
And it works fine. You might wanna edit the plugin to do this instead:
'click': function (e) {
e.preventDefault();
}
Alternatively you could look for a plugin that is developed by someone who knows what the hell they are doing or write it yourself.
In the documentation in http://zoomy.me/Options.html you can allow the plugin to have a clickable area by adding in true to the clickable option.
So when calling zoomy() on a element all you have to do is add a little bit of code inside the zoomy function.
$('.element').zoomy({clickable:true});
and that should fix everything,
The alternative way to catch the function on click event is just like below.
<div onclick="fireClickEvent();" > Just firing the click event!</div>
function fireClickEvent() {
console.log(event.target);
}