There will be number of such div created with unique div id,
when i click on click me it should show an alert for that productid,
i am doing it like
<div id="xyz{productid}">
Click Me
</div>
.....
<script type="text/javascript">
var uuid="{productid}"
</script>
<script src="file1.js">
code from file1.js
$(function () {
var d = "#xyz" + uuid;
$(d).click(function () {
alert("Hello" + uuid);
return false;
});
alert(d);
});
So code is also ok,but the basic problem with it is,
since i m doing it on category page where we have number of products,this function is getting bound to last product tile only,
I want it to be bound to that specific div only where it is been called
..............................
got a solution
sorry for late reply,was on weekend holiday, but i solved it by class type of architecture, where we create an object with each tile on page,and at page loading time we initialize all its class vars,so you can get seperate div id and when bind a function to it, can still use the data from its class variables, i m posting my code here so if any one want can use it,
UniqeDiv= new function()
{
var _this = this;
var _divParams = null;
var _uuid=null;
//constructor
new function(){
//$(document).bind("ready", initialize);
//$(window).bind("unload", dispose);
_uuid=pUUID;
initialize();
$('#abcd_'+_uuid).bind("click",showRatingsMe)
dispose();
}
function initialize(){
}
function showRatingsMe(){
alert(_uuid);
}
function dispose(){
_this = _divParams = null
}
}
//In a target file, im including this js file as below
<script type="text/javascript">
var pUUID="${uuid}";
</script>
<script type="text/javascript" src="http://localhost:8080/..../abc.js"></script>
You can use attribute selector with starts with wild card with jQuery on() to bind the click event for dynamically added elements.
$(document).on("click", "[id^=xyz]", function(){
//your code here
alert("Hello"+this.id);
return false;
});
I would add a class to each of your dynamic divs so that they are easier to query. In the following example, I'm using the class dynamic to tag the div's that are added dynamically and should have this click listener applied.
To attach the event, you can use delegated events with jQuery's on() function. Delegated events will fire for current and future elements in the DOM:
$(function() {
var d="#xyz"+uuid;
$(document).on('click', 'div.dynamic', function() {
alert("Hello"+uuid);
return false;
});
});
You can read more about event delegation here.
You can use
$("[id*='divid_']").click(function(){
});
but for this you need to make sure that all div IDs start with "divid_".
Related
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>
I'll try to explain my problem:
I have a website where the user dynamically adds elements. They all belong to the "toBuy" class. Whenever a new element is added to this class I need to attach a click-handler to only this element but not to all others. To keep my code clean I want to have a function that does this work. Here is what i've tried:
this is how the stuff is added:
$("#addItemButton").click(function(){
var item= $('#item').val();
$('#item').val("");
var quantity= $('#quantity').val();
$('#quantity').val("");
var comment=$('#addComment').val();
$('#addComment').val("");
//construct new html
var newitem="<div class='toBuyItem'><div class='item'>";
newitem+=item;
newitem+="</div><div class='quantity'>";
newitem+=quantity;
newitem+="</div><div class='comment'><img src='img/comment";
if(comment==""){
newitem+="_none"
}
newitem+=".png' alt='Comment'></div><div class='itemComment'>"
newitem+=comment;
newitem+="</div></div>";
$("#toBuyItems" ).prepend( newitem );
toggle("#addItemClicked");
initializeEventListeners();
});
then this is the initializeEventListeners function (which I also run when the page loads so that the existing elements have the event handlers already:
function initializeEventListeners(){
$(".toBuyItem").click(function(){
console.log($(this).html());
console.log($(this).has('.itemComment').length);
if($(this).has('.itemComment').length != 0){
console.log("toggling");
$(this).addClass("toggling");
toggle(".toggling .itemComment");
$(this).removeClass("toggling");
}
});
}
function toggle(item){
$( item ).slideToggle(500);
}
now apparently what happens is that when a new element is added the existing elements get a new event handler for clicking (so they have it twice). Meaning that they toggle on and off with just one click. Probably it's damn simple but I cannot wrap my head around it....
EDIT:
so this works:
$(document).on('click', '.toBuyItem', function(){
if($(this).has('.itemComment').length != 0){
console.log("toggling");
$(this).addClass("toggling");
toggle(".toggling .itemComment");
$(this).removeClass("toggling");
}
});
Use jquery's on method. This way you have to add event only once. This will be added automatically to dynamically added elements.
$(document/parentSelector).on('click', '.toBuyItem', function() {
// Event handler code here
});
If you are using parentSelector in the above syntax, it has to be present at the time of adding event.
Docs: https://api.jquery.com/on
You can use jQuery.on method. It can attach handlers to all existing in the DOM and created in future tags of the selector. Syntax is as follows:
$(document).on('click', '.toBuyItem', function(){
//do onClick stuff
})
As others have suggested, you can delegate click handling to document or some suitable container element, and that's probably what I would do.
But you could alternatively define a named click handler, which would be available to be attached to elements already present on page load, and (scope permitting) to elements added later.
You might choose to write ...
function buy() {
if($(this).has('.itemComment').length != 0) {
$(this).addClass("toggling");
toggle(".toggling .itemComment");
$(this).removeClass("toggling");
}
}
function initializeEventListeners() {
$(".toBuyItem").on('click', buy);
}
$("#addItemButton").on('click', function() {
var item = $('#item').val(),
quantity = $('#quantity').val(),
comment = $('#addComment').val();
$('#item', '#quantity', '#addComment').val("");
//construct and append a new item
var $newitem = $('<div class="toBuyItem"><div class="item">' + item + '</div><div class="quantity">' + quantity + '</div><div class="comment"><img alt="Comment"></div><div class="itemComment">' + comment + '</div></div>').prependTo("#toBuyItems").on('click', buy);// <<<<< here, you benefit from having named the click handler
$newitem.find(".comment img").attr('src', comment ? 'img/comment.png' : 'img/comment_none.png');
toggle("#addItemClicked");
});
I have the following html:
<div class="showMap" id="mapVis" style="cursor:pointer">(Show map)</div>
<div id="map">hello world</div>
Div #map is hidden as shown below (there's a reason for hiding it this way, it holds a google map), then I want to click (Show map) and the div appears. This is ok. Then I change the class and the html of the #mapVis div and want the next click to hide #map - but it doesn't. Honestly I don't know what its doing but its as if it ignores the new class and reverts to the actions as if previous class was still attached to the #mapVis div.
Here's the JQuery:
var map2 = $('#map');
map2.css('position','absolute').css('left','-9999em');
$('.showMap').click(function(){
map2.hide().css('position','relative').css('left','0em').slideDown();
$('#mapVis').removeClass('showMap').addClass('hideMap').html('(Hide map)');
});
$('.hideMap').click(function(){
map2.css('position','absolute').css('left','-9999em');
$('#mapVis').removeClass('hideMap').addClass('showMap').html('(Show map)');
});
Here's a fiddle
Since your selectors have to be evaluated dynamically you need to use event delegation.
When you use normal event registration the selectors are evaluated only at the time of event registration and any changes done on the element will not reflect in the registered handlers.
var map2 = $('#map');
map2.css('position', 'absolute').css('left', '-9999em');
$(document).on('click', '.showMap', function () {
console.log('hey2');
$('#map').hide().css('position', 'relative').css('left', '0em').slideDown();
$('#mapVis').removeClass('showMap').addClass('hideMap').html('(Hide map)');
});
$(document).on('click', '.hideMap', function () {
console.log('hey');
$('#map').hide();
$('#map').css('position', 'absolute').css('left', '-9999em');
$('#mapVis').removeClass('hideMap').addClass('showMap').html('(Show map)');
});
Demo: Fiddle
jsfiddle: http://jsfiddle.net/7At32/
this is a sample, BUT you can modify to your requirement
$('#mapVis').click(function () {
if ($(this).hasClass("showMap")) {
$('#map').show();
$(this).removeClass('showMap').addClass('hideMap').html('(Hide map)');
} else {
$('#map').hide();
$(this).removeClass('hideMap').addClass('showMap').html('(Show map)');
}
});
I have several jQuery click functions- each is attached to a different DOM element, and does slightly different things...
One, for example, opens and closes a dictionary, and changes the text...
$(".dictionaryFlip").click(function(){
var link = $(this);
$(".dictionaryHolder").slideToggle('fast', function() {
if ($(this).is(":visible")) {
link.text("dictionary ON");
}
else {
link.text("dictionary OFF");
}
});
});
HTML
<div class="dictionaryHolder">
<div id="dictionaryHeading">
<span class="dictionaryTitle">中 文 词 典</span>
<span class="dictionaryHeadings">Dialog</span>
<span class="dictionaryHeadings">Word Bank</span>
</div>
</div>
<p class="dictionaryFlip">toggle dictionary: off</p>
I have a separate click function for each thing I'd like to do...
Is there a way to define one click function and assign it to different DOM elements? Then maybe use if else logic to change up what's done inside the function?
Thanks!
Clarification:
I have a click function to 1) Turn on and off the dictionary, 2) Turn on and off the menu, 3) Turn on and off the minimap... etc... Just wanted to cut down on code by combining all of these into a single click function
You can of course define a single function and use it on multiple HTML elements. It's a common pattern and should be utilized if at all possible!
var onclick = function(event) {
var $elem = $(this);
alert("Clicked!");
};
$("a").click(onclick);
$(".b").click(onclick);
$("#c").click(onclick);
// jQuery can select multiple elements in one selector
$("a, .b, #c").click(onclick);
You can also store contextual information on the element using the data- custom attribute. jQuery has a nice .data function (it's simply a prefixed proxy for .attr) that allows you to easily set and retrieve keys and values on an element. Say we have a list of people, for example:
<section>
<div class="user" data-id="124124">
<h1>John Smith</h1>
<h3>Cupertino, San Franciso</h3>
</div>
</section>
Now we register a click handler on the .user class and get the id on the user:
var onclick = function(event) {
var $this = $(this), //Always good to cache your jQuery elements (if you use them more than once)
id = $this.data("id");
alert("User ID: " + id);
};
$(".user").click(onclick);
Here's a simple pattern
function a(elem){
var link = $(elem);
$(".dictionaryHolder").slideToggle('fast', function() {
if (link.is(":visible")) {
link.text("dictionary ON");
}
else {
link.text("dictionary OFF");
}
});
}
$(".dictionaryFlip").click(function(){a(this);});
$(".anotherElement").click(function(){a(this);});
Well, you could do something like:
var f = function() {
var $this = $(this);
if($this.hasClass('A')) { /* do something */ }
if($this.hasClass('B')) { /* do something else */ }
}
$('.selector').click(f);
and so inside the f function you check what was class of clicked element
and depending on that do what u wish
For better performance, you can assign only one event listener to your page. Then, use event.target to know which part was clicked and what to do.
I would put each action in a separate function, to keep code readable.
I would also recommend using a unique Id per clickable item you need.
$("body").click(function(event) {
switch(event.target.id) {
// call suitable action according to the id of clicked element
case 'dictionaryFlip':
flipDictionnary()
break;
case 'menuToggle':
toggleMenu()
break;
// other actions go here
}
});
function flipDictionnary() {
// code here
}
function toggleMenu() {
// code here
}
cf. Event Delegation with jQuery http://www.sitepoint.com/event-delegation-with-jquery/
I have dynamically generated some input tags for a web application.
function FormElement () {
this.formElement = $('<div class="formElement"></div>');
this.formElement.append('<label for=""></label>');
this.formElement.append('<input type="text" />');
FormElement.prototype.addIds = function (id) {
this.formElement.find('label').attr({'for':id});
this.formElement.find('input').attr({'id':id});
return this.formElement;
};
FormElement.prototype.addLabelText = function (value) {
this.formElement.find('label').html(value);
};
FormElement.prototype.addInputValue = function (value) {
this.formElement.find('input').attr({'value':value});
};
FormElement.prototype.addClass = function (className) {
this.formElement.attr({'class':className});
};
FormElement.prototype.append = function (selector) {
$(selector).append(this.formElement);
};
}
The appended elements do not seem to have associated click, select etc.. events. I read you can you .on(). I would like to associate all possible events to all types of elements in a general way. What is the best way to go about this?
Suppose you want to assign a default behavior on click event for all inputs with a specific class, say 'foo':
$(document).on('click','input.foo', function(){
/* your function here */
});
If you don't go this way and try the following:
$('input.foo').click(function(){
/* your function here */
});
then the behavior will be added only to existing elements, not to those added after the script executed.
you have to use On() function on them
Attach an event handler function for one or more events to the selected elements.
$("button").on("click", 'selector',notify);
$("target").on("change",'selector', notify);
For dynamically generated element's you need event delegation -
$(document).on('change','.yourInputClass',function(){
var value = $(this).val();
});
http://api.jquery.com/on/