jQuery select all elements with a common class - javascript

I want to handle a click event across a set of links so tried to approach this by adding a secondary class like following:
Test 1
Test 2
Test 3
Don't handle this one
Then tried this jquery selector to select the "external" class on links:
$('a.external').click(function(e) {
do something here...
});
However this isn't working like I expected. What's the right way to handle this? Should I just use a wildcard selector like the following or is there a better way?
$('[class^="someclass"]').click(function(e) {
....
});

What you have is exactly right (though the e probably isn't necessary in function(e) in your case).
Test 1
Test 2
Test 3
Don't handle this one
<script>
$('a.external').click(function(e) {
// will print the href in a javascript alert box
alert( $(this).attr('href') );
});
</script>
As far as I can tell the only possibility is that your <script> is actually above your <a> tags -- your script can't add the click listeners to the anchors because they wouldn't exist yet.
If so, you'll need to wrap the javascript in $(document).ready( function(){ /* code here */ });
Also, no need for the external class, just use the "select all absolute anchors, but not the ones linking to my domain" selector: $('a[href^="http://"]').not('[href^="http://mydomain.com"]')

I'm going to guess that your issue is that clicking the links actually makes it navigate somewhere? You need to tell the browser to ignore the normal link behavior. Otherwise your click function will run and then it will immediately navigate to the 'href' url. Also make sure this is all wrapped in a ready function.
$(function() {
$('a.external').click(function(e) {
// Do whatever
e.preventDefault();
});
});

I tried it out in jsFiddle and it works.
You have an extra parenthesis on the click() function.
Notice have your function(e) you have close parenthesis, remove that.
You should end up with this:
$('a.external').click(function(e) {
do something here...
});

try : http://jsfiddle.net/n6JJ3/
$('a.external').click(function() {
jQuery(this).css('background','red');
});​

Related

is this javascript code correct?

I am trying to remove a class when clicking on an element with a specific class. I made this javascript and it does work. But is this correct syntax to do it this way Can this be more efficient?
// Clear notifications alerts
$(document).on('click', '.js-clear-notifications', function() {
$('.AlertNotifications').remove();
});
// clear inbox alerts
$(document).on('click', '.js-clear-inbox', function() {
$('.AlertInbox').remove();
});
Your javascript code is correct, provided that you load jQuery as well.
Furthermore you have the most efficient solution, where you use a single event handler to handle events that originate on multiple elements.
The alternative would be:
$('.js-clear-notifications').on('click', function() {
$('.AlertNotifications').remove();
});
Which attaches as many event handlers as there are elements in the jQuery object. Slightly less efficient, though probably you would never notice except in extreme cases.
To me a more proper way to do it is something like this:
...
$('.js-clear-inbox').on('click', function() {
$('.AlertInbox').remove();
});
...
I will also suggest to have more specific selectors i.e.
$('div .js-clear-inbox')
I hope that this helps.
I am editing this in response to the feedback in the comments.
If what you want is to remove all elements with AlertNotifications class, which is what your code does, then what you have is correct.
If what you want is to remove only the class, which is what the text of the post said, you want removeClass, not remove:
$('.js-clear-notifications').on('click',function() {
$(this).removeClass('AlertNotificitions');
}
The new way, if you have already defined the variable, the proper way to delete it from the DOM would be:
var elem = document.getElementById("myDiv");
elem.remove();
But if you are just beginning out, .remove would be your best opinion.

Change Exposed elements (jQuery Tools )

I would like to cancel an exposed element and expose another one in one onClick(). Is that possible? My code doesn't work..
Here's the js:
function tutStep1(){
jQuery('#workspace_menu').expose({
onLoad: function(event) {
jQuery('.next').fadeIn();
}
});
jQuery('.tutorial .next').click(function() {
jQuery.mask.close();
tutStep2();
});
});
function tutStep2(){
jQuery('.action_list').expose();
}
Here's the html
<span onclick="tutStep1();" >tutorial</span>
The mask just won't open again unless I click on the span.
Or is there another way by not closing the mask, and switch elements to expose?
Probably not a good idea to put a click event inside a click event. I'm not familiar with this mask plugin, but speaking in the abstract, you can clean it up by doing something like this:
$('.open').click(function() {
$('#workspace_menu').show();
});
$('.tutorial, .next').click(function() {
$('.mask').hide();
$('.action_list').show();
});
Make sure you separate multiple selectors with a comma in the case of .tutorial and .next
You have your onClick events nested inside one another.
Recode and keep them all separate.

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

$('body').on('click', '.anything', function(){})

$('body').on('click', '.anything', function() {
//code
});
doesn't work for anything right now and I can't figure out why. I'm able to anchor to anything else, say I just toss a #wrap div right inside the body. Then I'm able to do
$('#wrap').on('click', '.anything', function() {
//code
});
for any element I want.
Any idea what I could have done to disable this ability on the body element?
Thanks!
You should use $(document). It is a function trigger for any click event in the document. Then inside you can use the jquery on("click","body *",somefunction), where the second argument specifies which specific element to target. In this case every element inside the body.
$(document).on('click','body *',function(){
// $(this) = your current element that clicked.
// additional code
});
You can try this:
You must follow the following format
$('element,id,class').on('click', function(){....});
*JQuery code*
$('body').addClass('.anything').on('click', function(){
//do some code here i.e
alert("ok");
});
If you want to capture click on everything then do
$("*").click(function(){
//code here
}
I use this for selector: http://api.jquery.com/all-selector/
This is used for handling clicks: http://api.jquery.com/click/
And then use http://api.jquery.com/event.preventDefault/
To stop normal clicking actions.

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