jQuery addClass onClick - javascript

The setting is easy; I want to be able to add a class to (in this case) a button when onClick-event is fired. My problem is that I haven't found a way to pass the button itself as the parameter to the function. I'd like to do something like:
<asp:Button ID="Button" runat="server" onclick="addClassByClick(this)"/>
And then a javaScript function something like this:
function addClassByClick(button){
button.addClass("active")
}
I know I've got a lot of errors here, but that's why I'm posting. I've tried different scenarios with jQuery and without jQuery but I always end up with a broken solution (clicks suddenly stop coming through, class not added etc etc) so I decided to ask the pro's.
Any suggestion to what I can try? Thanks for reading editand all the help!

It needs to be a jQuery element to use .addClass(), so it needs to be wrapped in $() like this:
function addClassByClick(button){
$(button).addClass("active")
}
A better overall solution would be unobtrusive script, for example:
<asp:Button ID="Button" runat="server" class="clickable"/>
Then in jquery:
$(function() { //run when the DOM is ready
$(".clickable").click(function() { //use a class, since your ID gets mangled
$(this).addClass("active"); //add the class to the clicked element
});
});

Using jQuery:
$('#Button').click(function(){
$(this).addClass("active");
});
This way, you don't have to pollute your HTML markup with onclick handlers.

$(document).ready(function() {
$('#Button').click(function() {
$(this).addClass('active');
});
});
should do the trick.
unless you're loading the button with ajax.
In which case you could do:
$('#Button').live('click', function() {...
Also remember not to use the same id more than once in your html code.

$('#button').click(function(){
$(this).addClass('active');
});

Try to make your css more specific so that the new (green) style is more specific than the previous one, so that it worked for me!
For example, you might use in css:
button:active {/*your style here*/}
Instead of (probably not working):
.active {/*style*/} (.active is not a pseudo-class)
Hope it helps!

Related

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);

how to add id to a html tag using jquery

I have more than one links with the class of video and I want to add an id attribute, When the user clicks on a link.
My code is :
$(function () {$(".video").click(function(e){
e.preventDefault();
$(this).attr('id', 'selected');
});});
After clicking the link, if i see the code. Firebug shows the same code without any change.
Try plain JavaScript:
this.id = "selected";
If that works, then it's a jQuery-fart. If it still doesn't work, make sure you're using Firebug correctly (I don't use it, but I know in IE I have to click a button to refresh the DOM view) and if that still doesn't seem to fix it use a class instead (or a data-* attribute)
There is nothing wrong with the code you posted so you are doing something wrong elsewhere. Here are a few general points of advice:
Format your code better to understand what is going on
Always wrap in an enclosed function that defines $ as jQuery incase
it is undefined or defined as something else in the global scope
Apply things like "selected" as classes, not ids
Don't use the short hand of document ready it is not descriptive of what it is doing and not readable
e.g.
(function($) {
$(document).ready(function() {
$('.video').click(function(ev) {
ev.preventDefault();
//$(this).attr('id', 'selected');
$(this).toggleClass('selected'); // This will turn the "selected" class on and off for each click
});
);
})(jQuery);

How to get the id of an element ON PAGE LOAD using jQuery

I simply know how to get the id of a clicked element it's like this:
$("button").click(function(){
console.log($(this).attr("id"));
}
but what can I do for getting the id on web page load? Look at this..
$("button").ready(function(){
console.log($(this).attr("id"));
}
it returns the whole document object and this one ..
$("button").load(function(){
console.log($(this).attr("id"));
}
simply does nothing.
I want to dynamically change the styles of all buttons on load.
The main project is more complicated, and I don't want to use js core to do it, I want the simplicity of jQuery selector, but equivalent js approaches are appreciated.
i want to dynamically change the styles of all buttons on load.
If that is the case you can simply apply the css to the button selector on load, without needing to get the id of each button.
$(function() {
$("button").css("background-color", "#C00");
});
Or better yet, put the css styling into a class and just apply a class to all the buttons:
$(function() {
$("button").addClass("red-bg");
});
If you did want to get the id of each button on load, you'd need to use an array to cater for the fact there may be more than one button:
var buttonIds = $("button").map(function() {
return this.id;
}).get();
However, this is a rather pointless method as you can just use each() to iterate over the button selector anyway to get access to each indiviual button element.
you can get the all button elements in jquery and then loop on each button element to change their style -:
$(function()
{
var allButtons = $('button');
$.each(allButtons,function(index,element)
{
$(element).css('width','100px');
});
});
I think you're looking for this:
$(document).ready(function () {
$(":button").each(function () {
console.log($(this).attr("id"));
})
});

Identical JQuery function is working for one link, not another

I have the function:
<script type="text/javascript">
$(function() {
$('#subbutton').click(function() {
$('#subbutton').hide();
});
});
</script>
It simply makes this button hide when clicked:
<a id="subbutton" class="button" href="javascript:TINY.box.show({url: 'follow',width:600,height:170,openjs:'initPopupLogin',opacity:30})"><span>Button</span></a>
Now, if i try to use the identical function, but with a link later on the page, it doesnt work (i have erased the original button at this point) Here is the code:
<div id="subbutton">
<span>Button</span>
</div>
I have tried putting the id in the anchor and in the span, nothing seems to be working for this link. Any idea why this isn't working? (I have deleted the original button so that this second button is a unique id on the page)
Try using .on instead to attach your event handler. I am suspecting the button is not in the dom at the time you attach the event handler.
$(document).on('click', '#subbutton', function() {
$(this).hide();
});
EDIT now that i understand the problem. You are better off giving the buttons a class and using a class selector.
.hide doesn't remove the element from the page so your selector will still be matching on the first element. You need to use .remove to remove the first element from the DOM so the second selector can work.
Also, little jQuery optimization. The nested call to $('#subbutton') is not needed. At best, it is harder to maintain, at worst, it could cause performance issues if you put this in a large loop. This is better.
$(function() {
$('#subbutton').click(function() {
$(this).remove();
});
});
You are missing a " after this:
<a id="subbutton" class="button
and Id has to be unique. Then it should work.
Don't reuse ids, they must be unique. pass the id to the function
Change your javascript to:
$(function() {
$('#subbutton').live("click",function() {
$(this).hide();
});
});​
http://jsfiddle.net/W2agx/
also don't reuse id's. use a class for multiple DOM elements that you want to be able to select together.

jQuery Class selector not working

I'm struggling to make an alert come up when an anchor tag with a specific class is clicked inside of a div.
My html section in question looks like this...
<div id="foo">
<a class='bar' href='#'>Next</a>
</div>
The jQuery section is as follows..
$('.bar').click(function()
{
alert("CLICKED");
});
My problem is that I cannot get this alert to come up, I think that I'm properly selecting the class "next", but it won't pick it up for some reason. I've also tried almost everything on this page but nothing is working. If I don't try to specify the anchor tag i.e. $('#foo').click(function()... then it works, but there will be multiple anchor tags within this div, so simply having the alert executed when the div is clicked won't work for what I need. The website this is on is a search engine using ajax to send information to do_search.php. Within the do_search.php I make pagination decisions based on how many results are found, and if applicable, a next, previous, last, and first link may be made and echoed.
EDIT: I just figured it out, it was my placement of the .next function, since it wasn't created on the initial document load but instead after a result had been returned, I moved the .next function to the success part of the ajax function since that is where the buttons will be created if they need to be, now it works.
Try using the live() command:
$(".bar").live("click", function(){ alert(); });
Because you load your button via AJAX, the click event isn't binded to it. If you use the live() command, it will automatically bind events to all elements created after the page has loaded.
More details, here
.live is now deprecated and is the selected answer for this. The answer is in the comments in the selected answer above. Here is the solution that resolved it for me:
$(document).on('click','.bar', function() { alert(); });
Thanks to #Blazemonger for the fix.
You surely missed $(document).ready(). Your code should be:
$(document).ready(function(){
$('.bar').click(function()
{
alert("CLICKED");
});
});
Hope this helps. Cheers
Make sure you have included JQuery Library properly.
Make sure your script has written between $(document).ready() in short $(function(){ });
Demo : http://jsfiddle.net/W9PXG/1/
<div id="foo">
<a class='bar' href='#'>Next</a>
</div>
$(function(){
$('a.bar').click(function()
{
alert("CLICKED");
});
});

Categories

Resources