jquery .click() event on dynamic anchor does not work - javascript

I have a <span class="clickspan">Some text here</span>
What I'm trying to do is when the span is clicked a dynamic anchor is created for the clicked span and then click event is triggered with jquery on the dynamic anchor.
$('.clickspan').on('click', function(){
// Method 1: Replace span with dynamic anchor
$(this).replaceWith('<a id="1234" href="www.example.com"></a>');
// None of the following works
$('#1234').trigger('click');
$('#1234').click();
// Method 2: Insert dynamic anchor inside the span
var theSpan = $(this).wrapInner('<a href="'+data.msg+'" donwload></a>'),
anch = theSpan.find('a');
// this click event on the dynamic anchor inside the span causes the click
// event on the parent span and to run the entire script all over again.
anch.click();
});
I've been struggling with this for a while and exhausted all ideas, so I'd appreciate any suggestion.
SOLVED
The method and the source suggested by #Ninsly in the comment below fixed the issue. The following worked:
$('#1234')[0].click();
Sorry for taking everybody's time. I was not aware of the need to use [0].

After creating the <a> tag bind the .click event to it then use the $('#1234')[0].click();.
Sometimes when you create dynamic html you have to then bind the events to the html you are creating.
Hope it helps :)

Method 1 works just fine, only you have to trigger the click event on the DOM element, not the jQuery object.
$(function() {
$('.clickspan').on('click', function() {
var anch = $('<a id="1234" href="http://harvest.com"></a>');
$(this).replaceWith(anch);
anch[0].click();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="clickspan">Some text here</span>
SPECIAL NOTE:
Most sites no longer allow display in a frame .... therefore the snippet might not show the site. See console output:
Refused to display 'https://www.google.com/' in a frame because it set 'X-Frame-Options' to 'SAMEORIGIN'. js:1
Refused to display 'https://www.yahoo.com/' in a frame because it set 'X-Frame-Options' to 'DENY'. js:1
Refused to display 'https://twitter.com/' in a frame because it set 'X-Frame-Options' to 'SAMEORIGIN'.

It looks like you want a redirect:
$('.clickspan').on('click', function(){
document.location.href = 'http//example.com';
});

Try this way:
$(document).on("click", '.clickspan', function(){
});
If elements are added dynamically you have to bind use listener on a hole document.

This may help you. Let me know. Here is the link to working demo http://jsfiddle.net/wu35uLt4/
$(function(){
function ondynAchorClick(){
alert('link auto clicked');
}
$('.clickspan').on('click', function(){
var _anch = $('<a id="1234" href="http://www.example.com"><span>Am link now</span></a>');
/*
Optionally you can add a handler if you don't want to redirect
_anch.click(ondynAchorClick);
*/
$(this).replaceWith(_anch);
_anch.find('span').click();
});
});

Related

Click on first onclick function inside tag by class selected

I'm new here ... so let me know how I can click on the first onclick within this div . Note that if you do $ (".giornoweekcorrente" ) i select the entire interior of the div but my problem is, how do I get to click the function visualizzaEvento ... through the class " giornoweekcorrente " .
Take a look for this image to understand.
Thanks for any help !
Try like this. Hope this helps.
$('.giornoweekcorrente a:first').click();
A possible workaround:
// get the first anchor child of the element and trigger the desired event:
$('.giornoweekcorrente').on('click', function(){
$('a', this).first().trigger('click');
});
var target = $(".giornoweekcorrente").children()[0]
$(target).click(function(){
visualizzaEvento();
});
just find the children of your div, and find the first child.
see : https://api.jquery.com/children/
Your anchor tag has an id why not use that:
$("#lente_click_gio").click();
Markus, you might want to attach "onclick" to the element with id "lente_click_gio" directly. You can do that using the following code:
$(document).ready(function(){
$("#lente_click_gio").on('click',function(){
//Your code here .. Call visualizzaEvento
});
});
But this would just attach the click event and the callback to it. Instead if you want to trigger a click event on the anchor element where you have attached the function, try the following code:
$("#lente_click_gio").click(); /* Generate a click event on the element with the ID lente_click_gio */
This would trigger a click event on that element. Hope this would help.

How to disable anchor element on load using jquery?

In my project , there is one anchor element as follows.
TRY NOW
I just want to disable the above anchor element when page completely loads. Actully I have used removeattr property of jquery. But I only want to disable the anchor element without removing onClick() event. So please help me in this question.
You say you'd like to keep your existing attribute handler. I suppose you're talking about handler definition, but not its processing, because that's what you're trying to prevent.
Solution 1: remove attribute completely
$(function(){
$(window).load(function(){
$("a").removeAttr("onclick");
});
});
Solution 2: change attribute code
$(function(){
$(window).load(function(){
var link = $("a");
var existing = link.attr("onclick");
link.attr("onclick", "return;" + existing);
});
});
Solution 3: change attribute but store definition
$(function(){
$(window).load(function(){
var link = $("a");
var existing = link.attr("onclick");
link.attr("data-onclick", existing)
.removeAttr("onclick");
});
});
This JSFiddle shows all three solutions. I've written it so that it doesn't change links on page load but rather simulates page load by clicking a link. Click any of the first three links first then simulate page load and click any link again and you'll see that all of them work.
You can try this
Using CSS
a{
pointer-events: none;
}
Dynamically using jquery
$(document).ready(function(){
$('a').css('pointer-events','none');
});
write script like below
$(window).load(function(){
$("a").removeAttr("onclick");
});

click event not working jQuery

I am trying to handle the click event using jQuery
on upload success, I am creating the following using jQuery:
$("#uploadedImage").append( "<div class='img-wrap'>
<span class='deletePhoto'>×</span>
<img data-id='"+files[i]+"' src='"+asset_url+"uploads/ad_photo/"+files[i]+"'>
</div>
<span class='gap'></span>");
and for handling click event for the above created div's I have written this:
$('.img-wrap .deletePhoto').click(function() {
var id = $(this).closest('.img-wrap').find('img').data('id');
alert(id);
});
the above code is working properly and creates all div, but when I click on the deletePhoto span. no jQuery alert is showing.
Any help or suggestion would be a great help.
Thanks in advance
delegate the event and change as suggested:
$("#uploadedImage").on('click', '.deletePhoto', function() {
You have to delegate your event to the closest static parent #uploadedImage in your case which is available on the page load like the container which holds the newly appended div and image.
although $(document) and $(document.body) are always available to delegate the event.
It is better to use on() when you create new element after DOM has been loaded.
$(document).on('click', '.img-wrap .deletePhoto', function() {
});
You are creating your element dynamically that is why you would need .live()
but this method is deprecated in newer version.
if you want to use jquery 1.10 or above you need to call your actions in this way:
$(document).on('click','element',function(){
`your code goes in here`
})
try this:
$(".img-wrap .deletePhoto").on('click', function() {
});
You can change a little in your code.
$(".deletePhoto").off("click").on("click",function(){
//Your Code here
});
First check in debugging mode that you get length when your code is going to bind click event and another thing bind event must written after that element is appended.
And Also check css of your element (height and width) on which you are clicking and yes
$(document).on('click','Your Element',function(){
//your code goes in here
});
Will works fine
use delegate:
$('#uploadedImage').on('click','.img-wrap .deletePhoto',function() {
var id = $(this).closest('.img-wrap').find('img').data('id');
alert(id);
});
see details delegate and .on here

clicking element in parent window

i have two windows.
One parent and the second an iframe. When a link is clicked inside of the iframe, i am able to effect the element in the parent window, but only certain things.
I am able to add Class without any problems, but when i want to trigger a click then it won't work.
Here is the working code for adding class:
parent window:
Name1
Name2
Name3
Name4
Name5
Iframe:
<div class="page5">link</div>
<script>
$('.page5').click(function(){
parent.top.$('#page5').addClass('classadded');
});
</script>
But when i try
<script>
$('.page5').click(function(){
parent.top.$('#page5').trigger('click');
});
</script>
nothing happens.
Any ideas?
Thanks
Jan
PS: their both on the same domain
Not a jQuery guy, but based on my testing at http://jsfiddle.net/kB3Jz/4/ , even when within the same frame, trigger is only working with jQuery-attached events, not the default click nor directly-DOM-attached events....
HTML:
Name5
<div class="page5">link</div>
JS:
$('.page5').click(function(){
$('#page5').trigger('click');
});
$('#page5')[0].addEventListener('click', function () {
alert('hello'); // Won't be triggered
});
$('#page5').click(function () {
alert('hello2'); // Will be triggered
});
The docs do say:
"For both plain objects and DOM objects other than window, if a
triggered event name matches the name of a property on the object,
jQuery will attempt to invoke the property as a method if no event
handler calls event.preventDefault()"
...so it would seem trigger should work (since clicking on the DOM object via $('#page5')[0].click() works), but for some reason, it doesn't--maybe it's simply that jQuery's expressed "attempt to invoke" has failed for some reason...
I'd therefore suggest changing window.location via a jQuery-added click handler on #page5
I would try
parent.location = parent.top.$('#page5').attr('href');
or
parent.location = parent.$('#page5').attr('href');

Allow clicking a link through a div that is bound to the "click" event

I have a div containing some content, in which there are some links. The div itself watches for the click event so it can make the content editable. However, I want the user to be able to click the links inside of the div and have it navigate to the linked page rather than edit the content (clicking anywhere else in the div should edit the content though). How do I achieve this?
Code example:
<div id="content">
Here's a link.
</div>
// jQuery Javascript:
$("#content").click(function() {
// Make content editable
});
(Clicking on the link shouldn't make the content editable, and instead should direct the page to google.com.)
Edit: I'm using my own code to make the content editable (switching out the div with a text area, that sort of thing).
Check the event target and return true
$("#content").click(function(e) {
if ($(e.target).is('a')) {
return true;
}
});
Not tested
The thinking behind this is to bail-out early from the handler and, by returning true, allow the browser to handle the event the usual way.
One error you have is that you are using content as a class in your HTML, but as an ID in your jQuery. So you should change your HTML to id="content" (assuming no other elements on your page already have that id.
Your Javascript can look like:
$("#content").click(function(){
this.setAttribute('contenteditable', 'true');
$(this).focus();
}).blur(function(){
this.setAttribute('contenteditable', 'false');
});
$("#content a").click(function(e){
e.stopPropagation();
});
Here's a JSFiddle: http://jsfiddle.net/q77Bs/
example
use event.stopPropagation()
// jQuery Javascript:
$(".content").click(function(e) {
// make content editable
});
$('.content a').click(function(e) {
e.stopPropagation();
});
You could change the z-index of the link to be greater than that of the div (not sure if that will work), or you can place each link inside another div with a higher zindex than the main div. This will prevent clicks from registering on the primary div, so make sure the secondary divs are correctly sized so as not to prevent the editing functionality
$('#content a ').live("click", function(event){
event.stopPropagation();
});
this will do the trick

Categories