I do not want to click twice to trigger an event - javascript

I am devloping a website in which I have created an option to upload multiple images using plupload script. Which allows us to trigger a popup when we click on an image to upload mulitple images.
This script requires a JS file to be added which has a function started with the code as below:
$(document).ready(function(){
var baseurl = $('#baseurl').val();
var i = 0;
$('.uploadFiles_one').click(function(){
$('#uploadBox_one').dialog('open');
return false
})
....
..some more js code..
....
})
Now I have modified this JS file so that I would be able to use the same JS file for multiple DOM element in which I have generated via PHP loop, the new script with the code as below:
$( document ).on( "click", ".uploadFiles_loop", function(){
var baseurl = $('#baseurl').val();
var i = 0;
var my_id = $(this).attr('id');
var cnt = my_id.replace("anchor_", "");
$('.uploadFiles_loop').click(function(){
$('#uploadBox_'+cnt).dialog('open');
return false;
});
....
..some more js code..
....
})
The front end would have one Image when any user click on the image it will open a popup. But now when I have modified the script I have to click twice on the image to get the popup. But after that all the rest Image uploader icons got open in single click.
So my question is why I have to click any "Upload Image" twice first time( I mean when the page has been loaded).

Try to remove this extra click handler $('.uploadFiles_loop').click(function(){...});
Leaving just:
$( document ).on( "click", ".uploadFiles_loop", function(){
var baseurl = $('#baseurl').val();
var i = 0;
var my_id = $(this).attr('id');
var cnt = my_id.replace("anchor_", "");
$('#uploadBox_'+cnt).dialog('open');
// Recheck were you want this return false;
return false;
....
..some more js code..
....
})
On your code you had a listener that on click run a function that added a click listener. So only by second click it would run the code $('#uploadBox_'+cnt).dialog('open'); return false;. If you remove that it will run on first click.
P.s. - On your code you have a return false;, if you have more code after it will not work. So I commented it, you might want it after the rest of you code you have.

$(document).ready(function(){
$( document ).on( "click", ".uploadFiles_loop", function(){
var baseurl = $('#baseurl').val();
var i = 0;
var my_id = $(this).attr('id');
var cnt = my_id.replace("anchor_", "");
$('#uploadBox_'+cnt).dialog('open');
return false;
});
....
..some more js code..
....
});
Very very unclear what you are trying to actually accomplish, however, you need to put the action you want to happen when you click, DIRECTLY IN the on function. Don't wrap it in another click function

Related

How can I observe changes to my DOM and react to them with jQuery?

I have this function where I toggle a class on click, but also append HTML to an element, still based on that click.
The problem is that now, I'm not listening to any DOM changes at all, so, once I do my first click, yup, my content will be added, but if I click once again - the content gets added again, because as far as this instance of jQuery is aware, the element is not there.
Here's my code:
(function($) {
"use strict";
var closePluginsList = $('#go-back-to-setup-all');
var wrapper = $('.dynamic-container');
$('#install-selected-plugins, #go-back-to-setup-all').on('click', function(event) {
$('.setup-theme-container').toggleClass('plugins-list-enabled');
if ( !wrapper.has('.plugins-container') ){
var markup = generate_plugins_list_markup();
wrapper.append(markup);
} else {
$('.plugins-container').hide();
}
});
//Below here, there's a lot of code that gets put into the markup variable. It's just generating the HTML I'm adding.
})(jQuery);
Someone suggested using data attributes, but I've no idea how to make them work in this situation.
Any ideas?
You could just do something like adding a flag and check for it before adding your markup.
var flag = 0;
$('#install-selected-plugins, #go-back-to-setup-all').on('click', function(event) {
$('.setup-theme-container').toggleClass('plugins-list-enabled');
if ( !wrapper.has('.plugins-container') ){
var markup = generate_plugins_list_markup();
if(flag == 0){
wrapper.append(markup);
flag = 1;
}
} else {
$('.plugins-container').hide();
}
});
If you want to add element once only on click then you should make use of .one() and put logic you want to execute once only in that handler.
Example :
$(document).ready(function(){
$("p").one("click", function(){
//this will get execute once only
$(this).animate({fontSize: "+=6px"});
});
$("p").on("click", function(){
//this get execute multiple times
alert('test');
});
});
html
<p>Click any p element to increase its text size. The event will only trigger once for each p element.</p>

Monitoring page use with jQuery/javascript

I plan to add some basic user usage of multiple html pages. To achieve this I want to introduce as little code changes to existing pages as possible. Here is my approach :
Import .js file that contains operations to add listeners to the page and when an event is fired then invoke a function :
<title>myTitle</title>
<input id="click" type="submit" value="click"/>
<input id="test" type="textbox" value="test"/>
<a id="href">href</a>
$('a').click(function(e) {
var linker = $(this).attr('id');
var title = $(document).find("title").text();
var url = window.location.href;
sendData(linker+'\n'+title+'\n'+url);
});
$('input').click(function(e) {
var linker = $(this).attr('id');
var title = $(document).find("title").text();
var url = window.location.href;
sendData(linker+'\n'+title+'\n'+url);
});
function sendData(dataToSend) {
console.log('Sending data \n '+dataToSend)
}
for now sendData is just a dummy function, but I plan to modify this to send an ajax request to server endpoint with the dataToSend value.
Is there an alternative method of monitoring what the user clicks instead of coding a tags and input tags ? There may be other input types that I'm not aware of that may get clicked that will not be tracked ?
fiddle :
http://jsfiddle.net/g2Rxc/167/
Because click events may be added after you've imported your listener code, you'll want to use event delegation on the document element.
Since you're running jQuery v 1.6, you'll need to use the delegate method:
$(document).delegate('*', 'click', function(e) {
var linker = $(this).attr('id'),
title = $(document).find("title").text(),
url = window.location.href;
sendData(linker+'\n'+title+'\n'+url);
return false;
});
Fiddle 1
Later versions of jQuery handle event delegation using the on method:
$(document).on('click', '*', function(e) {
var linker = $(this).attr('id'),
title = $(document).find("title").text(),
url = window.location.href;
sendData(linker+'\n'+title+'\n'+url);
return false;
});
Fiddle 2
I see that your click functions do the same thing so you can nest all the elements in a single click event:
$('a,input,textare,..,..').click(function(e) {
var linker = $(this).attr('id');
var title = $(document).find("title").text();
var url = window.location.href;
sendData(linker+'\n'+title+'\n'+url);
});
Try:
$("body").find("*").on("click",function()...
You just need to plan what do you want to track, before write the code. By doing that you are going to find which elements and events you really want to track. With that in mind you will write something like:
$('everyElementSeparatedByComma').on('everyEventSeparatedByComma', function(){
...
});
A real example:
$('a, input, textarea, form').on('click, change, keypress, submit', function(){
...
});

Why is jQuery .click() is skipped over?

I have a small script of javascript which iterates over a set of checkboxes which grabs the name attribute and value and then convert it to json. Then I use that value to set the href of an element and then try to trigger a click.
For some reason everything seems to function properly except for the click. I successfully change the href, I console.log() a value before the .click() and after. Everything hits except for the click. The url in the href is value as I clicked it manually.
I have my script included just before the closing body tag and have it wrapped in $(document).ready(). and I do not have duplicate ID's (I viewed the rendered source to check)
Can anyone offer some insight on this?
Here is the javascript
$(document).ready(function() {
$("#multiExport" ).on('click', function(e){
e.preventDefault();
var i = 0;
var list = new Array();
$('.appSelect:checked').each(function(){
var name = $(this).attr('name');
var id = $(this).val();
list[i] = new Array(name, id);
i++;
});
var serList = JSON.stringify(list);
console.log(serList);
var webRoot = $("#webRoot").text();
$("#exportLink").attr('href', webRoot+"/admin/admin_export_multiExport.php?emailList="+serList); //hits
console.log('1'); //hits
$("#exportLink").click(); //this line never executes
console.log('2'); //hits
});
});
$(selector).click() won't actually follow the link the way clicking on it with your mouse will. If that's what you want, you should unwrap the jquery object from the element.
$(selector)[0].click();
Otherwise, all you're doing is triggering event handlers that may or may not exist.
I may guess you need
$(document).on('click', '#multiExport', function(e){
(you can replace document by a nearest element, if you got one).
if you need dynamic click event binding.
EDIT
I would try something like that :
$(document).ready(function() {
$("#exportLink").click(function() {
window.location = $(this).attr('href');
});
$("#multiExport" ).on('click', function(e){
//whatever you want
$('#exportLink').attr('href', 'something').trigger('click');
});
});
$("#exportLink").click(); // this would launch the event.
I must admit I am very surprised that the .click() does not work.
If the idea is to load the page, then the alternative is
$(function() {
$("#multiExport" ).on('click', function(e){
e.preventDefault();
var list = [];
$('.appSelect:checked').each(function(){
var name = $(this).attr('name');
var val = $(this).val();
list.push([name, val]);
});
var serList = JSON.stringify(list);
var webRoot = $("#webRoot").text();
location=webRoot+"/admin/admin_export_multiExport.php?emailList="+serList;
});
});

jQuery .on() Not Working After Different Content Loaded

If you go to http://www.elemovements.com and try clicking "Read more..." on the first article, it will work, along with if you click the same link in the archive. This is all taken care of by this block of code... it's messy, yes, but I've been trying to figure various ways of doing it.
( function() {
var $Body = $("#news .inner");
var $Title = $("#news .title");
var strNewsURL = "<?=URL_NEWS?>";
$(document).on("click", "a:contains(Read More...)", function(event) {
var strOld = $Body.html();
var strURL = $(this).attr("href").replace("index.php", strNewsURL);
//var strBackURL = strURL.match(/archive.php/) ? "archive.php?xnewsaction=getnews&newsarch=" + getURLVars(strURL)['newsarch'] : strNewsURL;
$Body.slideUp(100);
$.get(
strURL,
objNHF,
function(strData) {
$Body.html(strData + '<a class="back"><?=TEXT_BACK?></a>').slideDown(1000, "easeOutBounce");
$(document).on("click", "#news a.back", function(event) {
$Body.slideUp(100, function() {
$(this).html(strOld);
} ).slideDown(1000, "easeOutBounce");;
event.preventDefault();
} );
}
);
track(strURL);
event.preventDefault();
} );
} )();
If you try loading another page (let's say, "Contact"), then click "Home" again, the event fires but does not load the content into the div. What am I doing wrong here? Very puzzling.
These variables are declared outside of your on/live click. When the new content is loaded, these elements are replaced and the variables point to the old copy.
var $Body = $("#news .inner");
var $Title = $("#news .title");
Move these variables inside the click so they are refreshed each time:
$(document).on("click", "a:contains(Read More...)", function(event) {
var $Body = $("#news .inner");
var $Title = $("#news .title");
...
I don't think you can use pseudo selectors for a delegated event handler. To fix this just use the HTML structure around the links to your advantage:
$(document).on('click', '.more a', function () {...});
This is a good idea anyway because the :contains pseudo-selector is quite slow. a:contains(Read More...) has to iterate through every link on the page and get it's text to check against.
Your selector is null
http://jsfiddle.net/qRWa5/21/

How to get the action performed by an hyperlink in javascript

How can i get the action performed by an hyperlink inside an div using javascript
<div id="example">
<a href="#">a<a>
b
c
</div>
var links = document.getElementById('example').getElementsByTagName('a');
links[0].onclick = function(){
alert('a clicked');
}
links[1].onclick = function(){
alert('b clicked');
}
links[2].onclick = function(){
alert('c clicked');
}
Working Example
you can attach event handlers in the loop as well:
var links = document.getElementById('example').getElementsByTagName('a');
for(var i = 0;i < links.length; i++){
links[i].onclick = function(e){
var event = e || window.event;
alert(e.target.innerHTML + ' link was clicked!!!');
}
}
I am guessing you are coming from a java background. So, action performed is not available by default in JavaScript. Neither is an anchor or <a>, an anchor is generally used to link to an external or internal links.
Goes to a mypage.html
Where As what you are asking by action performed is events. For that you should do something like this
Test Link
What this above link does is, executes a javascript function name test();
function test() {
alert('ok the action is performed');
return false; //so that the browser does not decides to navigate after the function is executed
}
Some javascript libraries will give you some workaround for this. Here is an basic example done in JQuery
$("#example a">.click(function() {
//now you have got the action performed work around.
// You can use this as you like
// $this represent the item that was clicked
});
For this functionality in core. #Headshota answers is good example.
#Headshota example of referencing all the links within a div is reasonable, I'm merely expanding on it. I'm not sure what you mean by the action of a link so I'm assuming that you mean the url it points to and perhaps the target (deprecated).
var links = document.getElementById('example').getElementsByTagName('a');
links[0].onclick = function(){
// `this` inside this handler points to the <a> element that has been clicked
var href = this.href //where the link points
var target = this.target //if required
//do something with href and target
return false; //don't follow the link
}
etc...
$("#example a").click(function() {
alert("action");
});

Categories