Getting the class name which triggered the event - javascript

I have a tag with below HTML :
<a href='#' class='create_account singup header-icon'>Create Account</a>
I am using a common click handler of the 3 button with Class create_account , member_login , product_service
Now inside the handler , I want the class name which triggered the click event, in best possible way (with minimal condition)
$('.create_account , .member_login , .product_services').click(function(){
console.log($(this).attr('class'));
/**
In case , user click on button with class `create_account` , I get in console
`create_account singup header-icon` , which is correct,
**but I want `create_account` i.e is the class which triggered the Click event**
*/
});

I would just create a separate click handler for each class, like so:
// Define all the required classes in an array...
var selectors = ["create_account", "member_login", "product_services"];
// Iterate over the array
$.each(selectors, function(index, selector) {
// Attach a new click handler per-class. This could be a shared function
$("."+selector).click(function(e) {
e.preventDefault();
alert(selector); // Logs individual class
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a class="create_account" href="">Create</a>
<a class="member_login" href="">Login</a>
<a class="product_services" href="">Services</a>
If you want you can abstract the shared logic out into another function, like this Fiddle

Alternative Approach with Data Attributes
<a href='#' class='action-trigger' data-action='Creation'>Create Account</a>
$('.action-trigger').click(function(){
console.log($(this).data('action'));
});
Retrieve Class Based on it Being First
<a href='#' class='create_account singup header-icon'>Create Account</a>
$('.create_account , .member_login , .product_services').click(function(){
console.log($(this).attr('class').split(' ')[0]);
});
Alternative Approach with Parameters
<a href='#' class='create_account singup header-icon'>Create Account</a>
$('.create_account').click(function(){
MyFunction('CreateAccount');
});
$('.member_login').click(function(){
MyFunction('MemberLogin');
});
function MyFunction(type)
{
console.log(type);
}

$(this).attr('class');
This will always return the list of classes that the element has. You can actually include an 'id' attribute to the element to access it when clicked.
<a href='#' class='but' id='create_account'>Button 1</a>
$('.but').click(function(){
alert($(this).attr('id'));
});
Demo: https://jsfiddle.net/dinesh_feder/2uq5h03j/

There are good solutions put forth using an array of selectors, but here is a solution using the strings of the selectors and the classes of the triggering element.
It's unfortunate that .selector was removed in jQuery 1.9 or else this would be even simpler. The approach is to get the original selector as an array and intersect it with the array of classes on the triggering element. The result will be the class that triggered the event. Consider this example:
[".create_account", ".member_login", ".product_services"]
[".class1", ".class2", ".create_account"]
Their intersection is:
[".create_account"]
Here is working code:
var selector = '.create_account, .member_login, .product_services';
$(selector).on("click", { sel: selector.split(", ") }, function(e){
var classArr = $(this).attr("class").split(" ").map(function(a){ return "."+a; });
var intersect = $.map(e.data.sel,function(a){return $.inArray(a, classArr) < 0 ? null : a;});
alert(intersect[0]);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="class1 class2 create_account">class1 class2 create_account</button><br/><button class="class3 product_services class4">class3 product_services class4</button><br/><button class="class5 class6 member_login">class5 class6 member_login</button>

I would add the classes into an array and then iterate to it to see if our target has one of those into its class attribute :
var classes = ['.create_account' , '.member_login' , '.product_services'];
$(classes.join()).click(function(){
for(var i=0; i<classes.length; i++){
var classPos = $(this).attr('class').indexOf(classes[i].substring(1));
if(classPos>-1)
$('#result').html(classes[i]);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href='#' class='create_account singup header-icon'>Create Account</a>
<a href='#' class='member_login singup header-icon'>Member Login</a>
<a href='#' class='singup header-icon product_services'>product services</a>
<p id="result"></p>

Well, to take back the Manish Jangir .... example, if you have to retrieve only the concerned class, then why don't you test it? you use jquery so you can use "hasClass" don't you?
$('.create_account , .member_login , .product_services').click(function(e){
if($(this).hasClass('create_account')){
alert('create_account');
}
if($(this).hasClass('member_login')){
alert('member_login');
}
if($(this).hasClass('product_services')){
alert('product_services');
}
});
This is maybe not a "perfect solution" but it fits your requirements...^^
You can also do it this way with jquery :
$('body').on('click','.create_account',function(event){
alert('.create_account');
//do your stuff
});
$('body').on('click','.member_login',function(event){
//...
});
$('body').on('click','.product_services',function(event){
//...
});
this way you just have to add a block if you add a new class that needs an event on click on it... I do not see any more "specific" answer to your question... I always used to do it this way since the way I handle the event on classes can be really different...

Related

Removing Class Using Jquery According to Parameter Value

I have the following button link:
×
And the following js:
function reEnableBtn(prodId) {
alert(prodId);
};
Until now all good, on click of the link I get an alert with the content: 573 as expected.
Next thing I want to do is with the following html:
<a href="/new-page/?add-to-cart=573" class="button product_type_simple add_to_cart_button ajax_add_to_cart added" data-product_id="573">
<i class="fa fa-shopping-cart finished disabled-button"></i>
</a>
Within the JS I want to add a removeClass function which removes the classes 'finished' and 'disabled-button' from the <i> where the data-product_id of the parent <a> matches the value of prodId within the JS function (because I have other links with same structure but different data-product_id).
How do I do this?
You can
1) use attribute equal selector to target anchor element with same data product id
2) find element i in above anchor element
3) use removeClass to remove multiple classes from it
function reEnableBtn(prodId) {
$('[data-product_id=' + prodId + '] i').removeClass("finished disabled-button");
}
function reEnableBtn(prodId) {
$("a[data-product_id='"+prodId+"']").find("i").removeClass("finished disabled-button");
};
Use this simple script.
Use this code
jQuery(function($){
var s = $("body").find('[data-product_id=573]');
s.on("click", function(e){
var i = $(this).find('i');
if (i.hasClass('finished'))
i.removeClass('finished');
if (i.hasClass('disabled-button'))
i.removeClass('disabled-button');
alert("The classes was removed.");
return false; // this is for disabling anchor tag href
});
})
jsfiddle
If you have any other question feel free to ask in comments.

how to Javascript toggle ID of div generated on runtime

I am sending a Model to a View in MVC,
and for each "Person" in my Model, I want to create a button that says "Show Details", when the user clicks it, a div with more information about that person toggles.
I am generating a a href and div id assigned to each person ID like the following:
foreach (var person in Model.Persons)
{
<div>
Show Details
</div>
<div id="#Html.Raw("detailsDiv-" + #person.id)">
<!--Content Here -->
</div>
}
I want to create the javascript that toggles on a click event
So I want to write this script but with the unique id for each person:
I want to get the id of the div that needs to be toggled.
I tried writing the script inside the foreach loop so I can be able to read the #person.id value, but it didnt work:
<script>
$(document).ready(function () {
$("#showDetails-#person.id").click(function () {
$("#details-#person.id").toggle();
});
});
</script>
Can anyone help?
put a class to your links like class="showDetails".
Now you Can create a global Event for all that links:
$('.showDetails').click(function(e) {
var id = this.id // extract id.. split with '-' or whatever..
$('#details-' + id).toggle();
});
you could put the id in a tag like "person_id" and use a class to trigger the jquery event.
<div class="middle_right">
<a class="showDetails" href="#" person_id="#Html.Raw("showDetails-" + #person.id)">Show Details</a>
</div>
and in js
$(".showDetails").click(function () {
var person_id=$(this).attr("person_id")
});

jQuery disable the previous span and the next span, on click span

I'm having trouble applying class to the previous element or the next element.
<a href="#"><span class="glyphicon glyphicon-thumbs-up up"></span>
<a href="#"><span class="glyphicon glyphicon-thumbs-down down"></span>
I want to disable the second span, when I click the first span and vice versa.
$(document).on('click','.up, .down',function (e){
e.preventDefault();
if ($(this).hasClass('up')){
var down = $(this).parent().nextAll('a.comment-vote-down');
down.removeClass('disable-link').addClass('disable-link');
}else if($(this).hasClass('down')){
var up = $(this).parent().prevAll('a.comment-vote-up');
up.removeClass('disable-link').addClass('disable-link');
}
});
example on jsfiddle
You try to find class .comment-vote-down that doesn't exist in your HTML code
https://jsfiddle.net/xnovq390/4/
try this:
$(document).on('click','.up, .down',function (e){
e.preventDefault();
if ($(this).hasClass('up')){
var down = $(".down");
down.removeClass('disable-link').addClass('disable-link');
}else if($(this).hasClass('down')){
var up = $(".up");
up.removeClass('disable-link').addClass('disable-link');
}
});
It's because you don't have an a with a class of .comment-vote-down, or comment-vote-up.
Either take that part out of your nextAll selection:
.nextAll('a');
https://jsfiddle.net/xnovq390/1/
or, add in the class to your HTML:
<a href="#" class="comment-vote-up">
https://jsfiddle.net/xnovq390/3/
If the .up element is always the previous element from the .down one, you can simply do:
$(document).on('click', '.up, .down', function(e) {
e.preventDefault();
if ($(this).hasClass('up')) $(this).next().addClass('disable-link');
else $(this).prev().addClass('disable-link');
}
$(document).on('click','.up, .down',function (e){
e.preventDefault();
if ($(this).hasClass('up')){
$(this).addClass('disable-link');
$('span.down').removeClass('disable-link');
}else if($(this).hasClass('down')){
$(this).addClass('disable-link');
$('span.up').removeClass('disable-link');
}
});
As the other answers already stated, there is no spoon element with .comment-vote-down class.
But additionally to make life easier, you could buffer the 2 elements, bind the click to them and disable the ones not clicked, reducing the code to
var btns = $('.up, .down');
btns.click(function(){
btns.not(this).addClass('disable-link');
});
fiddle
If you'd want to disable the containing a, the 'other's parent could be obtained by chaining parent() : btns.not(this).parent().addClass('disable-link'); ( or .closest('a') if there is a deeper hierarchy)

Parameter from <a href></a> to javascript

I have a <ul> <li> menu. When the <a> element inside the <li> is clicked, I need to run a Javascript function and this function needs some parameters like id or name. How can I do it? How can i send/retrieve parameters?
Example Javascript:
function addTab(title, uri) {
var tabNameExists = false;
$('#tabs ul li a').each(function(i) {
if (this.text == title) {
tabNameExists = true;
}
});
Example HTML:
<ul>
<li>W to set parameters
</ul>
link
function addTab(this)
{
$(this).attr('id');
$(this).attr('name');
}
Try
<a href="url" id="someUniqueID" title="SomeTitle" onClick = "addTab(this.title, this.href,this.id);" >link</a>
Your codes are not quite related to your question, anyway, here is the way:
<li>W to set parameters</li>
More logics can be made, depends on how you write some_js_function(id,name).
Note: If you want to fetch the attribute of the <a> or <li> tag , you can go with #PSR's answer.

JQuery Show/Hide Link

So here is my dilemma. Been trucking on this Jquery extreme code here and I need help telling if a certain link is showing or not. Here is what I have.
The toggles:
<span class="icon icon84"></span>
<span class="icon icon85"></span>
(notice the only thing that is different is the icon number) These need to toggle back and forth when someone clicks the #visbilitybutton. Not sure of the best way to do this and to capture what is selected as well.
The only code I have currently makes the toggle go one way, but doesn't go back when clicked again.
$(document).ready(function () {
$('#visbilitybutton').click(function() {
$(this).replaceWith('<span class="icon icon85"></span>');
});
});
First things first, you shouldn't have multiple identical id attributes on your page. Make visibilitybutton a class.
Anyways, you can use the jQuery toggle() function to specify what to do on each consecutive click:
$(".visibilitybutton").toggle(function(){
$(this)
.attr("title","Invisible")
.find("span").toggleClass("icon84 icon85");
}, function(){
$(this)
.attr("title","Visible")
.find("span").toggleClass("icon84 icon85");
});
If you want to be more efficient, you can do it all in one fell jQuery swoop like so, with some good techniques:
var vis = ["Invisible","Visible"];
$(".visibilitybutton").click(function(){
var i = 0;
$(this)
.attr("title",vis[i])
.find("span").toggleClass("icon84 icon85");
i = (i==0)?1:0;
});
Even more so would be to make a class that hides the element when added to it and shows it when you remove it (a classname with display:none applied in the CSS works fine):
$(".visibilitybutton").click(function(){
$(this)
.toggleClass("hide")
.find("span").toggleClass("icon84 icon85");
});
You need to have unique ids; therefore, you should select the items by class. You can use toggle() to handle the consecutive clicks, and you can use toggleClass() to handle the swapping of classes.
HTML:
<span class="icon icon84"></span>
<span class="icon icon85"></span>
Javascript:
$(document).ready(function () {
$('.button').toggle(function() {
var $button = $(this);
$button.prop("title","Invisible");
$button.find('.icon85').toggleClass('icon85', 'icon84');
}, function() {
var $button = $(this);
$button.prop("title","Visible");
$button.find('.icon85').toggleClass('icon84', 'icon85');
});
});
The id attribute is supposed to be unique to each element. Change the id attribute to the class attribute for each hyperlink.
Then, in your jQuery code, get the hyperlinks by their class name:
$('.visbilitybutton').click(function() {
// code goes here
});
In your event handler, you should use test the title attribute, like so:
$('.visibilitybutton').click(function() {
$this = $(this);
if ($this.attr("title") == "Visible")
$this.attr("title", "Invisible").find("span")
.removeClass("icon85").addClass("icon84");
else
$this.attr("title", "Visible").find("span")
.removeClass("icon84").addClass("icon85");
});

Categories

Resources