Doing the same function with Multiple click events in jquery - javascript

$(document).on('click','#closeNewProductExpand', function() {
$('#newProductExpand').css('width', '0');
});
$(document).on('click', '#searchProduct', function() {
$('#newProductExpand').css('width', '0');
});
$(document).on('click', '#productsData', function() {
$('#newProductExpand').css('width', '0');
});
Here I want to set the width to 0 of #newProductExpand if one of the above 3 buttons is clicked.Is there any way to write this code rather than wasting such a larger space.I appreciate your help.Thanks

you can combine selectors with comma.
$(document).on('click','#closeNewProductExpand, #searchProduct, #productsData', function() {
$('#newProductExpand').css('width', '0');
});
However, as an alternative I suggest you give all these elements a common class, and use that as the selector. That way, if you need to add more elements to the set, you just give them the same class, you don't need to make the list of selectors longer every time.

You can give the elements a class and simply target the class to make it easier instead of targeting the element IDs one by one.
Like this:
$('.className').click(function(){
$('#newProductExpand').css('width', '0');
});

Related

Using .on() and targeting elements with a specific attribute

I understand you can use .on() to attach a single click event to an element and then specify which child elements receive the click. So, for example:
$(this.el).on("click", "span", function () {
alert("Bloop!");
});
I need to be a bit more specific and target selectors with a particular attribute, like this:
$(this.el).on("click", "span[data-placeholder]", function () {
alert("Bloop!");
});
That doesn't seem to work, though. As soon as I add the attribute it stops working. No errors, just doesn't seem to find the elements.
Is that the expected behavior? Is there a way around it?
CLARITY
$(this.el) is just a div that contains a number of elements, some of which are <span data-placeholder="First Name"></span> tags. There could be dozens of those <span> tags and I didn't want that many event listeners, so I thought I'd use .on() to add the click to the parent container.
Here's JSFiddle showing your example working, with both existing <span>s and with newly created ones.
Just to be clear, this will work with your event delegation:
var span = $('<span>Test</span>');
span.attr('data-placeholder', 'test'); // declare as an attribute
$(this.el).append(span);
span.click();
This will not:
var span = $('<span>Test</span>');
span.data('placeholder', 'test'); // declare with .data()
$(this.el).append(span);
span.click();
jQuery's .data() method will read properties from data attributes if declared, but does not store them as attributes on the element when adding data.
Here's another JSFiddle.
try
$("span[data-placeholder]", this.el).on("click", function () {
alert("Bloop!");
});
You can choose to filter your spans
$('span', this.el).filter(function() {
return $(this).hasAttr('data-placeholder');
}).on('click', function() {
//This is for all the spans having data-placeholder
//...
});
Or if the placeholder is set via data api:
$(this.el).filter(function() {
return $(this).data('placeholder') != 'undefined';
}).on('click', function() {
//This is for all the spans having data-placeholder
//...
});
This functions above select those elements specifically, if event delegation on the OP is needed, then you can do the following:
$('span', this.el).on('click', 'span', function() {
if($(this).data('placeholder') != 'undefined') {
alert('bloop');
}
});
add a id to your span and pin point it using # tag

Using Jquery background to change css - How to Allow only one link at a time

I want to make a list of URLs that get highlighted when you click, the problem is only one link should be highlighted at any one time.
I'm able to get the reset button working. used removeAttr) - $("a").removeAttr("style") - (is there any negatives to doing it this way?)
But I can't get it to be only do one highlight at a time.
Could someone help me with an example code of making only one link highlighted at one time? Right now, it's possible to highlight multiple links.
I was able to make an example on Jsfiddle http://jsfiddle.net/M3vVw/3/
I'd recommend doing it this way: create a CSS rule and apply it to the element you click on, removing the same style from all links first.
jQuery
$("a").click(function () {
$('a').removeClass('back');
$(this).addClass('back');
});
$("#btn").click(function () {
$("a").removeClass("back")
});
CSS
.back {
background-color: #ff3fff;
}
jsFiddle example
I'd suggest using addClass() (as adeneo already suggested), but if you must use attr():
$('a').click(function(){
var that = $(this);
that.css("backgroundColor", "#ff3fff").closest('li').siblings().find('a').attr('style', '');
});
JS Fiddle demo.
Or:
$('a').click(function(){
var that = $(this);
that.css("backgroundColor", "#ff3fff").closest('li').siblings().find('a').removeAttr('style');
});
JS Fiddle demo.
Do remember that using attr()/removeAttr() is incredibly destructive and requires much more work and maintenance (you have to explicitly restructure the CSS of each of the styled element's properties every time); addClass()/removeClass() is far more efficient, since it contains all the styling externally, where it's easy to add/remove that styling to the element when needed.
References:
addClass().
attr().
closest().
css().
find().
removeAttr().
siblings().
You can use this:
$("a").click(function()
{
$(this).css("backgroundColor", "#ff3fff");
$("a").not($(this)).removeAttr("style");
});
$("#btn").click(function(){
$("a").removeAttr("style")
});
LIVE DEMO
CSS:
a.active{
background:#ff3fff;
}
jQuery:
function removeActive(){
$("a").removeClass("active");
}
$("a").click(function( e ){
e.preventDefault();
removeActive();
$(this).addClass("active");
});
$("#btn").click(removeActive);

Hiding button using jQuery

Can someone please tell me how I can hide this button after pressing it using jQuery?
<input type="button" name="Comanda" value="Comanda" id="Comanda" data-clicked="unclicked" />
Or this one:
<input type=submit name="Vizualizeaza" value="Vizualizeaza">
Try this:
$('input[name=Comanda]')
.click(
function ()
{
$(this).hide();
}
);
For doing everything else you can use something like this one:
$('input[name=Comanda]')
.click(
function ()
{
$(this).hide();
$(".ClassNameOfShouldBeHiddenElements").hide();
}
);
For hidding any other elements based on their IDs, use this one:
$('input[name=Comanda]')
.click(
function ()
{
$(this).hide();
$("#FirstElement").hide();
$("#SecondElement").hide();
$("#ThirdElement").hide();
}
);
You can use the .hide() function bound to a click handler:
$('#Comanda').click(function() {
$(this).hide();
});
jQuery offers the .hide() method for this purpose. Simply select the element of your choice and call this method afterward. For example:
$('#comanda').hide();
One can also determine how fast the transition runs by providing a duration parameter in miliseconds or string (possible values being 'fast', and 'slow'):
$('#comanda').hide('fast');
In case you want to do something just after the element hid, you must provide a callback as a parameter too:
$('#comanda').hide('fast', function() {
alert('It is hidden now!');
});
It depends on the jQuery selector that you use. Since id should be unique within the DOM, the first one would be simple:
$('#Comanda').hide();
The second one might require something more, depending on the other elements and how to uniquely identify it. If the name of that particular input is unique, then this would work:
$('input[name="Vizualizeaza"]').hide();

Do looping through items and adding handlers to it hurt performance

Does it hurt in performance when I loop through list-items and add a click-handler to all separate items?
The reason I do this is because I would only like to make the list item clickable if it contains an hyperlink.
The code I'm currently using is:
$('ul.paginator li').each(function() {
if ($('a', this).length > 0) {
$(this).css('cursor', 'pointer');
$(this).click(function() {
location.href = $('a', this).attr('href');
});
}
});
I'm not sure how much it might hurt performance, but have you considered using a somewhat simplified jQuery selector:
$('ul.paginator li:has(a)').each(
function(){
$(this).css('cursor','pointer').click(
function(){
location.href = $(this).find('a').attr('href');
});
});
Incidentally, the performance would depend on the number of elements you're searching through more than anything else. Just a few and it's likely to be imperceptible, a few thousand and it will (probably) be noticeable.
Edited to reduce the expense of has():
$('ul.paginator li a').each(
function(){
var address = this.href;
$(this).closest('li').css('cursor','pointer').click(
function(){
location.href = address;
});
});
This should be less expensive, as it will select only those a elements within an li, and then move up to affect that li element.
depends how many rows there are. If there are thousands of them, then yes. If there are a modest amount then not really enough to be noticeable.
An alternative approach would be to put the click handler on the element that contains the items, and then when a click event comes in, to use the data in the event passed to the handler to determine what to do. One handler.
Yes, it is better to use delegate with a proper selector that selects only the items you want.
There will be only one handler created and attached.
If you don't want to use has() than this will be enough (no need for multiple handlers):
$('ul.paginator').delegate('click', 'li', function() {
var link = $('a', this);
if (link.length > 0) {
location.href = link.attr('href');
}
});

Problem using toggleclass to change the span of the div

I am using blueprint CSS framework. I have an article spanning 24 cols but I trying to use jQuery toggleclass (onclick) to reduce it to 20 cols and show the buttons for actions in the remaining 4 cols.
$("div").each(function() {
$(this).click(function() {
$(this).toggleClass("span-24");
$(this).toggleClass("span-20");
});
});
I have more than one div so I use each, but it does not work.
I appreciate any help.
This code should do what you're after:
$("div").toggle(function() {
$(this).attr("class", "span-24");
}, function() {
$(this).attr("class", "span-20");
});
You can bind the click event to all divs without the each loop. Also, you can use the :gt() greater-than selector and then toggle() the visibility of those spans
$("div").click(function() {
$(this).find("span:gt(19)").toggle();
});
you don't want to toggle classes on all divs you have, rather just the one with content
you can even simplify this code more:
$('#toggler').click(function(){
$('#content').toggleClass('span-20 span-24');
});
the #toggler.click() is just one of events that can run the toggleClass(), in your HTML it could be onload or whatever:
$('#content').toggleClass('span-20 span-24'); //main code (and all of it, too)
example: http://jsfiddle.net/hhMFs/1/
You can also do this:
$("div").click(function() { $(this).toggleClass("span-20 span-24"); });

Categories

Resources