jQuery attr('onclick') - javascript

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.

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.

Reverse onClick Event

I am a genuine javascript novice and looking some pointers in my learning - not homework nor is it anything commercial.
I have a function here which shows an element which is hidden due to the first 2 lines of the function. I start by clicking the heading and the 2 hidden divs appear, which is exactly what I wanted to happen. However, now when I use this second function, it won't return to it's windown onload state. Why is this? Is there a better way to achieve this?
1st Function
$(window).ready(function(){
$('.miniC').css("display", "none");
$('.miniI').css("display", "none");
$(".heading").click(function(){
$('.miniC').slideDown();
$('.miniI').slideDown();
$('.miniC').show();
$('.miniI').show();
});
});
2nd Function (Reverse)
$(window).ready(function(){
$(".hideOut").click(function(){
$('.miniC').slideUp();
$('.miniI').slideUp();
$('.miniC').hide();
$('.miniI').hide();
});
});
Thanks in advance and any reference to good reading material is appreciated.
* Corrected Missing closing quote - this was a mistake of me typing it into Stack Overflow - Sorry! *
It seems like you want to toggle the visibility of an element, and since you're already sliding it, why not just use slideToggle:
$(".miniC").css("display", "none");
$(".miniI").css("display", "none");
$(".heading").click(function () {
$(".miniC").slideToggle();
$(".miniI").slideToggle();
});
Example
You shouldn't need to call .hide() and .show() - they will be dealt with as part of the slide functions. However, you're calling them immediately after the slide, but that takes a while to complete (400ms by default) meaning that .hide() fires before .slideUp() completes.
Outside the question scope, but still applicable.
$('.miniC').css("display", "none");
$('.miniI').css("display", "none");
This part of the page functionality should probably in CSS, which will result in the browser rendering the initial paint of the page correctly. In your case the browser paints the "miniC" and "miniI" elements, then your jQuery code updates the CSS display property to "none" for both individually. Triggering two additional repaints of the page. So, basically with the jQuery code you are drawing the page three times for an effect that could achieved with a single paint.
Then like Charlie said add a listener for the click.
$(".heading").click(function () {
$(".miniC").slideToggle();
$(".miniI").slideToggle();
});
Because slideUp() and hide() are written inside the click event. So, it wont fire on window ready, but only onclick of $(".hideOut").
There is a typo in your first function.
a single quote is missing in the line:
$('.miniC).show();

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

W3.org validation stuck on one inline javascript attribute, how to fix it?

I have a website with the following code for a specific element:
<textarea id="textToTranslate" onfinishinput="dothis()" rows="5"></textarea>
onfinishinput waits for the user input and check if he is stopped. If he stop typing, the function dothis is called throught $('#waitUserInput').live() function.
The tricky part of my question is, how to change the above line to be completely jQuery.
The jQuery dat correspont to the dothis() function is the following:
// Detect if user input stops
$('#waitUserInput').live("keyup", function(e)
{
startTypingTimer($(e.target));
});
var typingTimeout;
function startTypingTimer(input_field)
{
if (typingTimeout != undefined)
clearTimeout(typingTimeout);
typingTimeout = setTimeout( function()
{
eval(input_field.attr("onfinishinput"));
}
, 250);
}
Javascript dothis() function:
function dothis(){
// Ajax call when called
{
Now, when I go to http://validator.w3.org, I have one error, and yes it is about the above code:
Attribute onfinishinput not allowed on element textarea at this point.
<textarea id="textToTranslate" onfinishinput="dothis()" rows="5"></textarea>
The question is, is it possible to turn the onfinishinput javascript attribute out of the textarea, but so that is is functioning the same?
I know it is a little complex, but I hope someone can help.
Why not just change:
eval(input_field.attr("onfinishinput"));
To:
dothis();
And then remove the 'onfinishinput' attribute from your textarea?
There is no such attribute called 'onfinishinput' for the TEXTAREA so the validator is correct. Including it does in fact violate the standard.
It appears that what you are trying to do is to be able to have a different handler for each TEXTAREA on a page so that you can take different actions. If that is the case, why not just have your jQuery call dothis() unconditionally and pass the control that fired the event as a parameter?
You could then put control-specific handling in your dothis() function based on the ID of the passed control.
How about binding the event differently and removing the attribute:
$('#textToTranslate').bind('onfinishinput', dothis');
You'd then need to trigger the event using jQuery's trigger (see http://api.jquery.com/bind/)

A quick question about keypress and jQuery

$(document).keydown(function(e) {
Well, that's my code - I was wondering if it is possible to have something like:
$(document).not('#pinkElephant').keydown(function(e) {
(Except, that doesn't work...)
Any Ideas?
Thanks very much!
p.s. All that function has inside it, is a switch statement.
[edit] Hey guys n gals - I cannot return false; because the element I need to type in is an <input> text, so the keyboard still needs to return here.
It's really confusing me :(
Here's an alternate way to do what you require by checking to see that the target element's id isn't pinkElephant. Since this doesn't use the universal selector '*' it should perform better:
$(document).keydown(function(e) {
if (e.target.id !== "pinkElephant") {
alert("I'm not pink!");
}
});
Here's a working example.
(updated from comment)
If you really want to bind a keydown event handler to all nodes in your markup, with the exception of #pinkElephant you need to do it like this:
$(document).find('*').not('#pinkElephant').keydown(function() ..
or short
$(':not(#pinkElephant').keydown(function() ...
which implicitly uses the universal selector *.
Note, that this is never ever any good in terms of performance. I don't know your markup but I hope it's not very crouded using that kind of selector.
update
inspired by a comment, you could also do it like:
$(document).click(function(event) {
if( event.target.id === 'pinkElephant' || $.contains($('#pinkElephant')[0], event.target) )
return false;
// ...
});
Last snippet checks whether #pinkElephant itself or a child node was clicked and prevents the propagation + the default action. This is done by invoking $.contains()help
I assume you don't want elements inside pinkElephant to trigger the keydown.
Place a handler on #pinkElephant that stops propagation of the event.
$('#pinkElephant').bind('keydown',false);
Note that passing false to .bind() requires jQuery 1.4.3 or later.
If you're using an older version, do this:
$('#pinkElephant').bind('keydown',function(){return false;});
Try this instead:
$(':not(#pinkElephant)').keydown(function(e) {
// ...
});

Categories

Resources