passing event data dynamically in jquery - javascript

Please refer below HTML
<div class="Icon">
<span>
<img src=""/>
</span>
</div>
I am adding class "bootstrap-modal" dynamically to above IMG tag when it is clicked.
$(".Icon img").on("click", function (e) {
var data="some object";
$(this).addClass("bootstrap-modal");
});
Then i have one more click event for bootstrap-modal class like below
$(document).on('click',"bootstrap-modal" function (e,data) {
//here i need to get data object
});
how to pass data object from img click event to bootstrap-modal click event?
That means I need to get some values from previous click handler ?
How can I do this ?

Save it in data:
$('.Icon img').on('click', function(e) {
var data = 'some object';
$(this).addClass("bootstrap-modal").data('test', data);
});
$('.Icon').on('click', '.bootstrap-modal', function(e, data) {
var data = $(this).data('test');
});
FYI: Since you use the newest version of jQuery, you'd better use on method with event delegation instead of deprecated live. Here .Icon is supposed to be a static parent element of .bootstrap-modal.

Related

get object containing dynamic button jQuery

I have some dynamically created objects from a jade template which contain buttons. I would like to be able to get the object when the button inside it is clicked. Here is what I currently have
mixin ad(name,media,payout)
.box.box-primary
.box-header.with-border
h3.box-title=name
.box-body
img(src=media, style='width:130px;height:100px;')
p.text-muted.text-center="$"+payout
p.text-muted.text-center preview
.box-footer.text-right
button.btn.btn-primary(type='button',id="share",name="share",onclick='getSelf()') Share
and the jQuery
var getSelf = function() {
var clickedBtnID = $(this).parent();
alert('you clicked on button #' + clickedBtnID.name);
}
I know my jQuery is incorrect because It just prints "undefined" but how would I print the name?
Thanks.
As of now, this doesn't refer to the button element, it refers to window object.
You can pass the this reference to the function
button.btn.btn-primary(type='button',id="share",name="share",onclick='getSelf(this)')
Modify your function to accept the reference, which can be used later.
var getSelf = function(elem) {
var clickedBtnID = $(elem).parent();
alert('you clicked on button #' + clickedBtnID.name);
}
However I would recommend you to use unobtrusive event handler instead of ugly inline click handler(get rid of it).
$(function(){
$("#share").on('click', function(){
var clickedBtnID = $(this).parent();
alert('you clicked on button #' + clickedBtnID.name);
});
})
You can reference to the element which triggered the event using the event.target property. The event information is passed as the first parameter to the event handler.
Complete working code.
$('div').click(function(event){
console.log(event.target.id)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="div1">div1</div>
<div id="div2">div2</div>
<div id="div3">div3</div>
<div id="div4">div4</div>
<div id="div5">div5</div>

Defining a single jQuery function for separate DOM elements

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/

Binding click function to dynamic divs

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_".

No events for dynamically generated input tags

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/

Javascript Function get elements contents

I was using a listener to trigger a certain code:
$(".item-actions > .like-button").click(function (e) {
oid = $(this).parent().attr('data-oid');
alert(oid);
});
Now instead of a listener I'm simply calling the function on the HTML.
CLICK
I'm having problems getting the element's content, and parent content as I'm not able to use $(this) to select them. How can I do the same I was doing with the function?
I first tried this which didn't work:
function alertOID() {
oid = $(this).parent().attr('data-oid');
alert(oid);
}
How can this be done?
Is it what you are looking for?
<input class="like-button" onClick="alertOID.call(this);">
on .like-button html onclick event call alertOID() like this alertOID(this)
<input class="like-button" onClick="alertOID.call(this);">
instead of
<input class="like-button" onClick="alertOID.call();">
and change alertOID like this
function alertOID(element) {
oid = $(element).parent().attr('data-oid');
alert(oid);
}

Categories