Javascript- send the clicked object as parameter in onClick function - javascript

In function clickCircle, i want to use the li which is being clicked. So i want to receive it as a parameter.
<li class="circle" onClick='clickCircle(this)'></li>
But what should i send as an actual paramenter? ie in place of 'this'.

You can use this:
function clickCircle(obj) // the li element clicked in the current scope
{
var element = obj; // This is the DOM object being clicked
var $this = $(obj); // This is the jQuery object being clicked
// Use DOM object like
element.style.color="#ff0000";
// Use jQuery object like
$this.css('color', 'red');
}

Try this instead
<li class="circle"></li>
$('.circle').on('click', function(event) {
event.target // your element
});

You should just use the first parameter as the element.
HTML
<li class="circle" onClick='clickCircle(this)'></li>
JS
clickCircle=function(element)
{
console.log(element)
console.log(element.tagName) // This will show LI
}
JSFiddle: http://jsfiddle.net/edi9999/WhVLm/

you can do it with jquery like this:
$(function () {
$('li.circle').on('click', function () {
clickCircle($(this));
});
});
var clickCircle = function (param) {
// your code here
// param.css('color', 'red').html();
};
or with raw javascript:
HTML
<li id="circle" class="circle"></li>
JAVASCRIPT
var circle = document.getElementById('circle');
circle.addEventListener('click', function (e) {
clickCircle(e.target);
});
var clickCircle = function (param) {
// your code here
// alert(param.nodeName.toLowerCase());
}

Related

Pass a reference of the button I'm clicking into the func it triggers. JS

How do I pass a reference of the button I am clicking into the function it triggers?
jQuery('<button class="btn"/>')
.click(function() {
myFunc(this??);
return false;
})
var myFunc = function (this??) {
//I WANT TO CHECK IF THE BUTTONS PARENT HAS A SPECIFIC CLASS HERE
if(jQuery(this??).parent().hasClass('myClass')){
//DO STUFF HERE
}
}
I can't use the class name as there are several of these buttons on my page.
Use myFunc(this). Its correct way to passs the element to your function
Use any other name other than this for your function parameter.
jQuery('<button class="btn"/>')
.click(function () {
myFunc(this);
return false;
});
var myFunc = function (elem) {
//I WANT TO CHECK IF THE BUTTONS PARENT HAS A SPECIFIC CLASS HERE
if (jQuery(elem).parent().hasClass('myClass')) {
//DO STUFF HERE
}
}
No need to pass it in a separate function
jQuery('<button class="btn"/>')
.click(function() {
if(jQuery(this).parent().hasClass('myClass')){
//DO STUFF HERE
}
return false;
})
Remove ?
jQuery('<button class="btn"/>')
.click(function() {
myFunc(this);
return false;
})
var myFunc = function (obj) {
//I WANT TO CHECK IF THE BUTTONS PARENT HAS A SPECIFIC CLASS HERE
if(jQuery(obj).parent().hasClass('myClass')){
//DO STUFF HERE
}
}
this is a reserved word and cannot be used as a variable (which is what you're attempting to do within your myFunc function. Change the name of your variable in your myFunc declaration:
var myFunc = function (myElement) { ... }
Then change your if statement to reflect that change:
jQuery(myElement).parent().hasClass('myClass')
I dont have much knowledge about jquery but a possible solution using Js is
<script>
function onClick1(b)
{
alert(b.parentNode.className);
}
</script>
<div class="divClass">
<button onclick="onClick1(this)">
hello
</button>
</div>
we can pass "this" in the onclick event attribute, which passes the reference object of the element generating the event (in this case button). We then can reference the parentNode of button and its class with className property.
HTML
<div class="myClass">
<button id="btn" class="btnClass">Hi</button>
</div>
JS
$('.btnClass').click(function() {
myFunc(this);
});
var myFunc = function (a) {
//I WANT TO CHECK IF THE BUTTONS PARENT HAS A SPECIFIC CLASS HERE
if(jQuery(a).parent().hasClass('myClass')){
alert();
//DO STUFF HERE
}
}
Check This Example

Function works with onClick but not using an eventlistener

I've created a function to toggle a class on and off an element with a certain id. It works like this with onclick in the html:
HTML:
<a href="#menu" class="menutoggle" onclick="toggle(className);">
<h2id="menubutton">Menu</h2>
</a>
<ul id="menutoggle" class="hidden">
JavaScript:
var toggle = function (className) {
var toggleclass = document.getElementById(className); // identify element to change
if (toggleclass.className === "hidden") { // if class = hidden
toggleclass.className = "shown"; // change to shown
}
else { //if not hidden
toggleclass.className = "hidden"; // change to hidden
}
};
However if I try to use the function with an eventlistner, I'm out of luck:
HTML:
<a href="#menu" class="menutoggle">
<h2 id="menubutton">Menu</h2>
</a>
<ul id="menutoggle" class="hidden">
JavaScript:
var toggle = function (className) {
var toggleclass = document.getElementById(className); // identify element to change
if (toggleclass.className === "hidden") { // if class = hidden
toggleclass.className = "shown"; // change to shown
}
else { //if not hidden
toggleclass.className = "hidden"; // change to hidden
}
};
var tog = document.getElementsByClassName("menutoggle")[0];
tog.addEventListener("click", toggle(className), false);
I cannot figure out what I'm doing wrong. Your help is much appreciated :)
The second argument of addEventListener needs to be a function.
You aren't passing it a function. You are calling the toggle function and passing its return value. Since toggle doesn't have a return statement, that value is undefined.
If you want to call toggle with a specific argument, you can bind.
tog.addEventListener(
"click",
toggle.bind(this, className),
false);
Replace this with whatever you want the value of this to be inside the function (since you don't use this there, it doesn't matter what that is).
Make sure you define className, you don't anywhere if the code in the question.
If you need to support IE8 or earlier, then you can create a new function instead of using bind:
tog.addEventListener(
"click",
function () { toggle(className) },
false);

Get ID of Element Being Clicked and Pass as Parameter?

How does one, through jQuery, get the ID of an element that is being clicked on and then pass it as a parameter into a function? Example jQuery code below.
jQuery(document).ready(function() {
var id = this_id;
jQuery(".lightbox a").click({param: id}, functionName);
});
May I note that the "param" parameter is integral to the structure of the function.
Apologies all, I am no Javascript master by any means.
I'm guessing the point is to pass event data to a function that expects that, as ,click() supports the .click( [eventData ], handler(eventObject) ) syntax, and if so, you have to iterate the collection yourself:
jQuery(document).ready(function($) {
$(".lightbox a").each(function() {
$(this).click({param: this.id}, functionName);
});
});
EDIT:
You could do this with on() as well:
jQuery(document).ready(function($) {
$(".lightbox a").each(function() {
$(this).on('click', {param: this.id}, functionName);
});
});
FIDDLE
Within the click handler, you can access the element ID with this.id or $(this).attr('id'):
jQuery(document).ready(function() {
jQuery(".lightbox a").click(function(){
functionName(this.id);
});
});
You can use this.id inside a click event, example:
jQuery(".lightbox a").click(function() {
var id = this.id;
//pass to a function
testFunction(id);
});
function testFunction(param) {
console.log(param);
}
It's easy just access to the this element to get the clicked element, then extract its id and save it into a variable like this:
jQuery(".lightbox a").click(function(){
var id = jQuery(this).attr("id");
callFunction(id);
});
http://jsfiddle.net/pArW6/
jQuery(document).ready(function() {
jQuery(".lightbox a").click(functionName);
});
function functionName()
{
alert(this.id);
}
You can you Use $(this).att("id").
$(".lightbox a").click(function() {
var ID=$(this).att("id");
//pass to a function
TestFunction(ID);
});
function TestFunction(P) {
console.log(P);
}
Live example
http://jsbin.com/enobop/1/edit
You can do this:
jQuery(document).ready(function () {
jQuery(".lightbox a").click(function (e) {
// Cancel the default action (navigation) of the click.
e.preventDefault();
// 'this' here refers to the link being clicked in the current scope
// you can check the console for the id for debug purpose
console.log(this.id);
// pass the id to the function
functionName(this.id);
});
});
Another way is to use the event parameter that gets passed to the callback function.
jQuery(".lightbox a").click(function(ev) {
console.log(ev.target.id);
}
Of course it's a mix of jQuery and pure JS.
Usually you have a function for an event declared with
function(event)
and the event has a target and the id of the target is, what you want. So
$("SomeElement").on("click", function(e){ callanotherFunction(e.target.id) })
does, what you wanted
You can use this.id or $(this).attr("id");, but you might want to get a reference to $(this) - wrapped or not - immediately and work from a variable if you do much of anything else in there.

Confused with calling JQuery custom function

I have html like so
<span rel='comm' val='12'>click</span>
<span rel='comm' val='82'>click</span>
and I am using JQuery to do this
$('span[rel*=comm]').cust();
and the custom function is as such
$.fn.cust = function () {
$(this).click(function(e) {
alert($(this).val());
});
}
The value of this is 12 even when I click on 2nd span which should give me 82
Any help would be appreciated.
You'll need to return a seperate function for each element in the collection, normally done with return this.each ...
$.fn.cust = function () {
return this.each(function() {
$(this).click(function(e){
alert($(this).val());
});
});
}
And value is not a valid attribute for a span element.
This should work better:
$.fn.cust = function () {
$(this).click(function (e) {
alert($(this).attr('val'));
});
}
span does not have value.
http://jsfiddle.net/dREj6/
Also if you want to make your method chainable you should return an jQuery instance:
$.fn.cust = function () {
return $(this).click(function (e) {
alert($(this).attr('val'));
});
}
$('span[rel*=comm]').cust().css('color', 'red');
http://jsfiddle.net/dREj6/1/
rel are for links (anchor element) - use class
use data attribute instead of custom attributes
http://jsbin.com/ogenev/1/edit
<span class='comm' data-val='12'>click</span>
<span class='comm' data-val='82'>click</span>
$.fn.cust = function(){
$(this).click(function(){
alert(this.dataset.val);
});
};
$('.comm').cust();
It works if you use .attr('val')
$.fn.cust = function () {
$(this).click(function(e){
alert($(this).attr('val'));
});
}
$('span[rel*=comm]').cust();
http://jsfiddle.net/fW7FT/
.val() is for input since they're the only one accepting the val attribute officialy
The call $('span[rel*=comm]') returns a JQuery wrapper for all spans matching the selector - the two ones you have in your example are picked both.
Now inside the definition of cust, $(this) refers to the wrapped array, which causes your issue. Use
$(this).each( function() {
$(this).click (...
});
Inisde each $(this) will point to each separate span element in the selection, so they will have the click handler individually attached and working as you expect.
You can achieve what you're looking for with this:
HTML:
<span rel='comm' val='12'>click</span>
<span rel='comm' val='82'>click</span>
JS:
var cust = function(source) {
alert($(source).attr('val'));
}
$('span[rel*=comm]').click(function(e) {
cust(this);
});
The JSFiddle working: http://jsfiddle.net/ejquB/

Call a function onClick and passing it a value from the element's data-* attribute

I have links like this:
<li>Get codes</li>
<li>Get products</li>
How can I make it so that when I click on the link then a function gets called passing the value that's contained in data-value?
function refreshGrid(value) { }
Try the following:
$('li > a[href="#"][data-value]').click(function (e) { // On click of all anchors with a data-value attribute and a href of # that are immediate children of li elements (nb this selector can be modifed to suit your needs)
e.preventDefault(); // prevent the default (navigate to href)
refreshGrid($(this).data('value')); // call your refreshGrid function with the value contained in the 'data-value' attribute
});
var linkValue = $("li a").attr("data-value");
Edit: Better example
$("li a").click(function () {
var myDataValue = $(this).attr("data-value");
refreshGrid(myDataValue);
});
here's a quick sample
$('ul').on('click','a[data-value]',function(){
refreshGrid(this.getAttribute('data-value'));
return false;
});

Categories