is this javascript code correct? - javascript

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.

Related

How to set an element that I am toggling to be collapsed on load

I am struggling to figure out how to make an element that I am toggling on click with jQuery collapsed when the page initially loads. Everything is open on load at the moment - exactly the opposite of what I need.
Keeping in mind that I'm a beginner, can someone please help me? Thanks.
// Toggle
$('.togglehandle').click(function() {
$(this).toggleClass('active');
$(this).next('.toggledata').slideToggle();
});
// alert close
$('.clostalert').click(function(){
$(this).parent('.alert').fadeOut ();
$('#options').hide();
});
First off, remember to set your ".toggledata" element to display: none in the CSS.
Also, make sure that the two handlers you posted are all wrapped in $(document).ready(). In other words, make sure you have something like the below:
$(document).ready(function() {
// Toggle
$('.togglehandle').click(function() {
$(this).toggleClass('active');
$(this).next('.toggledata').slideToggle();
});
// alert close
$('.clostalert').click(function(){
$(this).parent('.alert').fadeOut ();
$('#options').hide();
});
});
And just because you mentioned that you are a beginner..........here it is with just a little code cleanup ;)
$(document).ready(function() {
// Toggle
$('.togglehandle').on('click', function() { //1: .click() -> .on('click',
var $this = $(this); //2: $(this) -> var $this = $(this)
$this.toggleClass('active');
$this.next('.toggledata').slideToggle();
});
// alert close
$('.clostalert').on('click', function(){
$(this).parent('.alert').fadeOut(); //3: No change
$('#options').hide();
});
});
Explanation of changes:
Changing .click() to .on('click'...
The .click() method is just shorthand for the .on('click'... method. Using the long form doesn't really have any benefits over the shorthand, except that it standardizes your handler bindings and has more options for parameters (like when using delegated events, which you will likely do in the future).
Changing $(this) to var $this = $(this)
This part is sometimes difficult to wrap your mind around. First and foremost, understand that jQuery, itself, is actually a function object. The developers of jQuery gave the library two names that can both be used interchangeably when coding: $ and jQuery.
In other words, both of the following are actually equivalent:
$('.toggledata').slideToggle();
and
jQuery('.toggledata').slideToggle();
This is important because it must be remembered that the $ is essentially a function name, used like any other. As such, each time you call $(this) you are essentially calling a "constructor" function to initialize a new jQuery object. As such, to make code more efficient, we store $(this) in a variable so that it can be reused.
The variable name $this is just a convention (a good one that you should make a habit of using). It is a common convention to prefix the name of any variables that hold jQuery objects with the dollar sign. For example, if we store $('.clostalert') in a variable then we would do something like:
var $clostalert = $('.clostalert');
Notice that we do not bother to store $(this) in a variable in the second handler because it is only used once and thus $(this) is only called once there.

JavaScript alert callback not working inside a function

I am trying to make a image preview containing of about 5-6 images which will appear one after another when user hovers over it (not like a carousel with prev and next buttons). Here is the fiddle consisting of what I gathered so far.. i don't know if this approach is right or not.. but I am stuck as the alert callback is not working. Could someone please tell me what is wrong?
$(function()
{
var imageCount = $('#product_grid_list').find('figure')[0].getElementsByTagName('img');
for (var i = 0, n = imageCount.length; i < n; i++) {
imageCount[i].on('click', function(e)
{
alert('Everything is going fine!');
}
);
}
}
);
The root cause of click event callback can't be triggered is that you're trying to register a event handler on a "DOM" (in this case: imageCount[i]) element in jQuery way. Try to register the event handler like this if you want to use pure javascript solution:
imageCount[i].addEventListener('click', function(e){
alert('Everything is going fine!');
});
Here is a jsfiddle demo.
Note: I didn't consider the cross browser issue in this case.
BTW, try to cache the length of imageCount node list, it will improve the performance.
You are using js AND jQuery at same time. It's wrong. If you use jQuery, than click event will be like this:
$(document).('click', '#product_grid_list figure img', function(){
alert('Everything is going fine!');
});
You are using a mix of jQuery and standalone javascript. You might as well go all the way to jQuery, with something like:
$('#product_grid_list figure:first img').click(function(e) {
alert('Everything is going fine, hopefully!');
});
You did not send the corresponding HTML, so we cannot test whether the above is correct.
it's just a simple click event in jQuery, no need to use js: http://jsfiddle.net/wP3QQ/11/
$('#product_grid_list').find('figure img').click(function(e){
alert('Everything is going fine!');
e.preventDefault();
});
You want the hover effect, so click event should not be used over here. It should be mouseover.
Working Fiddle
Code Snippet:
$(document).on('mouseover','#product_grid_list figure img',function(e){
alert("now it is working");
});
You are attempting to call on(), a jQuery method, on an HTMLElement (a DOM element). You can't do that, jQuery methods can only be called on jQuery collections. It's easy to get a jQuery collection for the elements you desire:
Use .find() to match the images
There's no need for a for() loop, jQuery's .on() will handle looping for you.
You may also want to prevent the default behaviour of your anchors
$(function () {
var imageCount = $('#product_grid_list').find('figure img');
imageCount.on('click', function (e) {
e.preventDefault()
alert('Everything is going fine!');
})
});
JSFiddle

Devil of a time with jQuery delegate and .not

I've searched hi and low but couldn't find a solution. I've tried everything.. but can't get this thing to work.
NOTE: Can't use ".on()" . Using an older version of jQuery that only supports .live/.delegate
basically, I have a very involved webpage.. and there are event handlers flying everwhere.. BUT, I basically want to attach a click event on the body BUT exclude certain id's. Great. Figured it would be easy.
tried:
jQuery('body').delegate('.not("#mainID #anotherID")','click', function(e){
// do something
})
jQuery('body').delegate(':not(".class1 .class2")','click', function(e){
// do something
})
etc...
and a bunch bunch more.. basically, cannot get this thing to work. No matter what I do, the whole page is clickable.
when I do something simple like: Great it works.
jQuery('body').delegate('#someID','click', function(e){
// do something
})
But that isn't what i need. I need to basically allow for clicking on the whole body except for two subsets, smaller sections of the page. I figured this would be trivial.. but for some reason, just not working.
The two items I want to exclude are:
id: mainID w/ a class of ".class1"
id: anotherID w/ a class of ".class2"
another note: mainID sits outside of anotherID - two distinct sections of the page. Both divs.
Let me point out few things related to event delegation:
First of all, use .on() function, .delegate() is deprecated.
Second, .class1 .class2 will match class2 which is inside of class1
jQuery('body').on('click', ':not(.class1, .class2)', function(e) {
// do something
})
But, this is also not what you need, you need:
$(".class1, .class2").on('click', function() { return false; });
If you are using older versions of jQuery and for some reason cannot change it, use .live() or normal .click() handler:
$(".class1, .class2").click(function() { return false; });
Now, if you click on .class1 and .class2 nothing will happen. If you want to select only specific class within a id you can use #mainID .class1 as selector. Or with older event delegation:
jQuery('body').delegate(':not(.class1, .class2)','click', function(e){
// do something
// but this will execute on every where you click except .class1, .class2
})

jQuery select all elements with a common class

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');
});​

jQuery attr('onclick')

I'am trying to change "onclick" attribute in jQuery but it doesn't change, here is my code:
$('#stop').click(function() {
$('next').attr('onclick','stopMoving()');
}
I have an element with id="stop" and when user clicks on it I want to change an onclick attribute on element which has id="next".
If someone knows where is the solution please help!
Do it the jQuery way (and fix the errors):
$('#stop').click(function() {
$('#next').click(stopMoving);
// ^-- missing #
}); // <-- missing );
If the element already has a click handler attached via the onclick attribute, you have to remove it:
$('#next').attr('onclick', '');
Update: As #Drackir pointed out, you might also have to call $('#next').unbind('click'); in order to remove other click handlers attached via jQuery.
But this is guessing here. As always: More information => better answers.
As #Richard pointed out above, the onClick needs to have a capital 'C'.
$('#stop').click(function() {
$('next').attr('onClick','stopMoving()');
}
The easyest way is to change .attr() function to a javascript function .setAttribute()
$('#stop').click(function() {
$('next')[0].setAttribute('onclick','stopMoving()');
}
Felix Kling's way will work, (actually beat me to the punch), but I was also going to suggest to use
$('#next').die().live('click', stopMoving);
this might be a better way to do it if you run into problems and strange behaviors when the element is clicked multiple times.

Categories

Resources