How to append something just one time using jQuery? - javascript

I want to add Jack in the end of a string only one time. How?
$('button').click(function() {
$('div').append('Jack');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<div>My name is: </div>
<button>click</button>
In other word, when I click on that button, if Jack is appended, then nothing happens, but if Jack is not exist, then it appends.

$('button').click(function() {
$('div').html('Jack');
});
This will replace whatever is inside the div

$('button').click(function() {
var text = $('div').text();
if(!/Jack/.test(text)){
$('div').append('Jack');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<div>My name is: </div>
<button>click</button>

Use jQuery's on() and off() methods to easily control when event listeners are active.
To add an onclick listener:
$("button").on("click", function(){});
To remove the listener:
$("button").off("click");
In your case, you can put the off() function call inside of the on() function's callback. The result is an anonymous function that will run once, on a single click, and then remove itself.
$("button").on("click", function(){
$("div").append("Jack");
$(this).off("click");
}
Or even better, use one(), which will fire only once per element.
$("button").one("click", function(){
$("div").append("Jack");
}

Related

How do I select a class but not its inside element?

Say I have
<div id="mydiv">
<div class="myclass">
<span class="otherclass"></span>
and many other classes...
</div>
</div>
I want to capture the click event on .mydiv but not inside .myclass.
I tried .mydiv:not(.myclass) but it doesn't seem to work. I think it's because I might be clicking on the otherclass so the :not(.myclass) is not working. How can I get the area I want to get? Thanks!
make #mydiv clickable, do whatever you wish, and stop event propagation from .myclass, so the event will not bubbleup from myclass to mydiv
$('#mydiv').click(function(){
// do anything
})
// stop event propagation
$('.myclass').click(function(e){
e.stopPropagation();
})
You can click on mydiv id and write your code in that function and on .myclass click event you simply write return false to stop further execution of function.
$('#mydiv').click(function(){
// stuff your code here
});
//Use `return false` instead of `e.stopPropagation();`
$('.myclass').click(function(e){
return false;
})
e.stopPropagation() is dangerous please read Documentation
Calling .off() will remove an event handler
$("#mydiv").on('click', function () {
alert("You clicked mydiv");
});
$(".myclass").off('click', function () {
});
or like this
$(".myclass").off();
JS FIDDLE

I'm having a jQuery onclick issue

So I'm going to explain this with an example.
I have a "like" button (class: .like) for my feed or stream. When the user clicks it ( using $(".like") ), it ajaxes it's way to refreshless insert the like into the database (using jQuery).
When it's inserted, I change the text to "Unlike" and the class to ".unlike".
However, when a user reclicks it, it just goes through the same function again, instead of going to the $(".unline").click function. Do I have to "update" the script or something?
For example:
$(".like").click(function(){
alert("Like!");
$(this).attr("class", "unlike");
});
$(".unlike").click(function(){
alert("Unlike!");
$(this).attr("class", "like");
});
The problem is that it won't to the unlike function, it will just repeat the like function even though the attribute is changed.
That is because the "unlike" attr. hasn't been added to the dom when the script loaded. Try this:
<body>
<div class="like_it_or_not">
HELLO!
</div>
</body>
And the JS
$("body").on('click','.like_it_or_not', function(){
$(this).toggleClass('like', 'unlike');
if ($(this).hasClass('like')) {
alert('like');
} else if ($(this).hasClass('unlike')) {
alert('unlike');
}
});
If you don’t want to delegate your click event (which is over-engineering IMO), do a check in the handler:
$(".like").click(function(){
alert( $(this).hasClass('unlike') ? 'unlike' : 'like' );
$(this).toggleClass("unlike like");
});
http://jsfiddle.net/NScyM/
It should check for the 'unlike' class each time you click and toggle classes as expected.
The event binding occurs when you assign run the above code. You have to rebind the event every time, or, better yet, use event delegation:
$(document)on("click",".like",function(){
alert("Like!");
$(this).addClass("unlike");
$(this).removeClass("like");
});
$(document)on("click",".unlike",function(){
alert("Unike!");
$(this).addClass("like");
$(this).removeClass("unlike");
});
I think you will have to use live() or on() to make this work:
$(".like").live("click", function() {
$(this).removeClass("like").addClass("unlike");
});
$(".unlike").live("click", function() {
$(this).removeClass("unlike").addClass("like");
});
Try this one
$(".like").click(function(){
alert("Like!");
$(this).removeClass("like");
$(this).attr("class", "unlike");
});
$(".unlike").click(function(){
alert("Unlike!");
$(this).removeClass("unlike");
$(this).attr("class", "like");
});
To keep my code clean on stuff like this, I assign a class that never changes and tie the click event to that. The styling classes simply act as CSS changes. For instance:
<button class="vote like">button text</button>
$('.vote').click(function () {
var alertText = ($(this).hasClass('like')) ? 'Like!' : 'Unlike!';
alert(alertText);
$(this).toggleClass('like').toggleClass('unlike');
});
Try this
$(document).on('click', '.like', function(){
alert("Like!");
$(this).html('Unlike').removeClass("like").addClass("unlike");
});
$(document).on('click', '.unlike', function(){
alert("Unlike!");
$(this).html('Like').removeClass("unlike").addClass("like");
});
DEMO.
The unlike click event handler has not been associated with the new item. If you're going to be changing the class dynamically like that you're going to want to look at the (jQuery on handler)[http://api.jquery.com/on/]
$(document).on('click',".like", function(){
alert("Like!");
$(this).addClass("unlike").removeClass('like');
});
$(document).on('click',".unlike",function(){
alert("Unlike!");
$(this).addClass("like").removeClass('unlike');
});

Access dynamically created items using jQuery?

I have a page where some html is being dynamically added to the page.
This is the html and javascript that is created:
<div>
<script type="text/javascript" language="javascript">
$('#btn').click(function() {
alert("Hello");
});
</script>
<a id="btn">Button</a>
</div>
Looking in my Firebug console, I get an error that says:
TypeError: $("#btn") is null
jQuery is being loaded on the page initially.
What am I doing wrong here?
You have to bind on() (or the events defined within the on() method, to an element that exists in the DOM at the point at which the jQuery was run. Usually this is on $(document).ready() or similar.
Bind to the closest element in which the $('#btn') element will be appended that exists in the DOM on page-load/DOM ready.
Assuming that you're loading the $('#btn') into the #container div (for example), to give:
<div id="container">
<div>
Button text
</div>
</div>
Then use:
$('#container').on('click', '#btn', function(){
alert('Button clicked!');
});
Use .on to wire up the event to your button. Check this SO answer:
Event binding on dynamically created elements?
$(document).ready(function() {
$('body').on('click', '#btn', function() {
alert("Hello");
});
})
Edit: I added the document ready code, you'll want to make sure you do that.
Fixed.
you are looking for .on here which will bind the click event to dynamically added nodes.
$("#parent_container").on("click", "#btn", function () {
alert("hello")
})
the docs: http://api.jquery.com/on/
Try
<div>
<a id="btn">Button</a>
</div>
<script>
$('#btn').on('click', function() {
alert("Hello");
});
</script>
The problem in your code is that you are attaching the event to the button before the button is being created.
Correct version is:
<div>
<a id="btn">Button</a>
<script type="text/javascript" language="javascript">
$('#btn').click(function() {
alert("Hello");
});
</script>
</div>
This should do the job.
Use the .live() function of jQuery

Scope in jQuery(javascript)

I simplified my code for next example. So, please don't be wondered why I'm using ajax here.
<!DOCTYPE>
<head>
<style>.not { background:yellow; }</style>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
$(document).ready(function() {
$(".not").click(function(e){
e.stopPropagation();
alert('good');
});
$(".click").click(function(e){
$.post('page2.php', 'q=1', function(data){
$('body').append('<p class="click">Click here to add new paragraph <span class="not">[not here]</span></p>');
}, "json");
});
});
</script>
</head>
<body>
<p class="click">Click here to add new paragraph <span class="not">[not here]</span></p>
</body>
New rows don't make any alert for class=not! It is inexplicably for me :'(
Thanks for unswer!
Assuming jQuery 1.7.x, use this:
$(document).on('click', ".not", function(e){
alert('good');
}).on('click', ".click", function(e){
if(!$(e.target).is('.not')) {
$('body').append('<p class="click">Click here to add new paragraph <span class="not">[not here]</span></p>');
}
});
The problem is, .click will only bind to elements that exist when it's called. Using .on the way I'm suggesting delegates the click handling to the document element. By passing a selector as the second argument, you tell jQuery to run the event handler only if the event target matches the selector.
Put the $(".not")... part inside a function, such as disableNot = function() {$(".not").click......}. Then, after appending the new paragraph, call disableNot() to update the event handlers. (Also call disableNot immediately after defining it, so any .not elements already on the page are given their handlers.)
In your ready event handler, you use $('.not).click. click is an alias for bind, and bind only works on elements that are already in the DOM.
If you're using jQuery 1.7, you can use on instead, in its delegate-like form.

jQuery function not binding to newly added dom elements

Here's index.html:
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('.btn_test').click(function() { alert('test'); });
});
function add(){
$('body').append('<a href=\'javascript:;\' class=\'btn_test\'>test</a>');
}
</script>
</head>
<body>
test1
add
</body>
If I click on test1 link, it shows alert('test'), but if I click on add link then click on test, it doesn't show anything.
Could you explain it?
For users coming to this question after 2011, there is a new proper way to do this:
$(document).on('click', '.btn_test', function() { alert('test'); });
This is as of jQuery 1.7.
For more information, see Direct and delegated events
You need to use a "live" click listener because initially only the single element will exist.
$('.btn_test').live("click", function() {
alert('test');
});
Update: Since live is deprecated, you should use "on()":
$(".btn_test").on("click", function(){
alert("test");
});
http://api.jquery.com/on/
I have same problem like question I was just near to pulling my hair then i got the solution.
I was using different syntax
$(".innerImage").on("click", function(){
alert("test");
});
it was not working for me (innerImage is dynamically created dom)
Now I'm using
$(document).on('click', '.innerImage', function() { alert('test'); });
http://jsfiddle.net/SDJEp/2/
thanks #Moshe Katz
.click binds to what is presently visible to jQuery. You need to use .live:
$('.btn_test').live('click', function() { alert('test'); });
Use Jquery live instead. Here is the help page for it http://api.jquery.com/live/
$('.btn_test').live(function() { alert('test'); });
Edit: live() is deprecated and you should use on() instead.
$(".btn_test").on("click", function(){
alert("test");
});
This is because you click event is only bound to the existing element at the time of binding. You need to use live or delegate which will bind the event to existing and future elements on the page.
$('.btn_test').live("click", function() { alert('test'); });
Jquery Live
you need live listener instead of click:
$('.btn_test').live('click', function() {
alert('test');
});
The reason being is that the click only assigns the listener to elements when the page is loading. Any new elements added will not have this listener on them. Live adds the click listener to element when the page loads and when they are added afterwards
When the document loads you add event listeners to each matching class to listen for the click event on those elements. The same listener is not automatically added to elements that you add to the Dom later.
Because the event is tied to each matching element in the document ready. Any new elements added do NOT automatically have the same events tied to them.
You will have to manually bind the event to any new element, after it is added, or use the live listener.
$('.btn_test').click
will add the handler for elements which are available on the page (at this point 'test' does not exist!)
you have to either manually add a click handler for this element when you do append, or use a live event handler which will work for every element even if you create it later..
$('.btn_test').live(function() { alert('test'); });
After jquery 1.7 on method can be used and it really works nice
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js">
</script>
<script>
$(document).ready(function(){
$("p").on("click",function(){
alert("The paragraph was clicked.");
$("body").append("<p id='new'>Now click on this paragraph</p>");
});
$(document).on("click","#new",function(){
alert("On really works.");
});
});
</script>
</head>
<body>
<p>Click this paragraph.</p>
</body>
</html>
see it in action
http://jsfiddle.net/rahulchaturvedie/CzR6n/
Or just run the script at the end of your page
You need to add a proper button click function to give a proper result
$("#btn1").live(function() { alert("test"); });

Categories

Resources