Jquery appending with styling and functions - javascript

i appending buttons with some IDs and i use those IDs to make on click stuff
when it appending didn't take button() effect
and on click it don't take the function that I created it for this button id
$("button#edit-doc").each(function() {
$(this).button();
$(this).on("click", function(){
alert("clicked");
});
});
append button
$("#append").on("click", function(){
$('div#container').append("<button id='edit-doc'> Edit </button>");
});
container
<div id="container"></div>

This seems to be what you're after:
function handler() { alert('clicked'); }
$("#append").on("click", appendButton);
function appendButton(){
$('#container').append(function() {
return $("<button id='edit-doc'> Edit </button>").on("click", handler);
})
}
http://jsfiddle.net/PF8xY/
See jQuery how to bind onclick event to dynamically added HTML element for more information on this behavior.

$(document).on("click", "#selector", function(){
//Your code here.
});
Using document for your selector with .on will allow you to bind events to dynamically created elements. This is the only way I've found to do it when the DOM elements don't exist prior to execution.
I do this in a dynamically created table that is sort-able and works great.
EDIT:
Here is an example. Click the button to add a div then click the div to get it's contents.
http://jsfiddle.net/FEzcC/1/

The first code-block attaches an event listner to all buttons with class='edit-doc', use classes instead of an id since an id's name may only exist once per page. So I was saying, when your browser reaches this code an event listner is added to all available buttons in your document at that moment. It doesn't add an event listner to buttons you will be adding later onclick of some element, because it doesn't know. You will have to explicitly execute the code again for the buttons that you append. But what you don't want is to add a new event listner to the original buttons, causing two events being called.
Something like:
// Load all buttons with class=edit-doc and add event listner
$(function() {
$("button.edit-doc").button().on("click", function(){
alert("clicked");
});
});
// Append button if button with id=append is clicked
$("#append").on("click", function(){
var button = $.parseHTML("<button class='edit-doc'>Edit</button>");
$('div#container').append(button);
$(button).button().on("click", function(){
alert("clicked");
});
});
Working example:
http://jsfiddle.net/RC9Vg/

Related

Trying to write a function from inline javascript

I've got some code from a developer that left our company. He wrote an inline function looking like this:
<button class="xxx" id="MyID" type="button" onclick="javascript: $('#openThis').slideToggle('slow');">btnText</button>
I've tried to remove this and put it in another function to write a callback so I can scroll to the toggled area when it's visible.
$("#MyID").click(function () {
$("#openThis").slideToggle("slow");
});
But I can't seem to get it to work. What am I doing wrong?
are you adding the listener before or after the object is created on the DOM?
because if you are trying to bind that onclick function without waiting the document to be ready theres no object to create the listener.
something like this could work:
$(document).on('ready', function() {
$("#MyID").click(function () {
$("#openThis").slideToggle("slow");
});
});
If you button is added dynamically then use on instead of click
Attach an event handler function for one or more events to the
selected elements.
Event handlers are bound only to the currently selected elements; they
must exist at the time your code makes the call to .on()
//Instead of document you can use a container id
$(document).on('click',"#MyID",function () {
$("#openThis").slideToggle("slow");
});
What this approach does is it adds event to a currently selected element which is document here and it will delegate the event to your selector which is #MyID in this case.
Delegated events have the advantage that they can process events from
descendant elements that are added to the document at a later time.
$(document).on('click', '#myBtn', function(){
$('#foo').slideToggle('slow');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<div id="foo">content</div>
<button id="myBtn">Click me</button>
You want to scroll to the area so remove the JavaScript from the button
You need to do something like this
$("#MyID").click(function() {
$('html, body').animate({
scrollTop: $("#openThis").offset().top
}, 2000);
$("#openThis").slideToggle("slow");
});
You should delete the onclick="" attributes in the button tag and in your javascript :
$("#MyID").click(function (e) {
e.preventDefault();
$("#openThis").slideToggle("slow");
});
Use the prevent default.
Hope that help

Adding event listener on a replaced HTML DOM

I am using the tooltipster jquery plugin to show title in a nicer way. In my site there is a link with two classes .fav tooltip
<div class="actsave">
Save
</div>
The .tooltip is use to take the above anchor title and display it according to the tooltipster plugin.
$('.tooltip').tooltipster();
This works just fine, but when a user will click on this link the entire DOM will be replace with a new DOM.
$("div.actsave").on("click", "a.fav", function(e){
e.preventDefault();
$(this).replaceWith('Delete');
});
At this point no events are occurring with the new anchor with .del class.
My question is how i can add a event listener to this newly created dom in jquery?
After doing some research i fix it this way:
$("div.actsave").on("mouseover mouseout", "a.del", function(e){
$(e.target).tooltipster();
});
but it seems that we are adding same event again and again without any reason to the dom when we hover the link, so here is the question can we add an event listener to this newly created dom just for once?
$("div.actsave").on("click", "a.fav", function(e){
e.preventDefault();
var newElement = $('Delete');
$(this).replaceWith(newElement);
newElement.tooltipster();
});
Create a flag to keep track using data()
$("div.actsave").on("mouseover mouseout", "a.del", function (e) {
if (!$(this).data('triggered')) {
$(e.target).tooltipster();
$(e.target).data('triggered', true);
}
});

Second jQuery button click isn't firing

I am trying to do something ostensibly simple in jsfiddle and it is not working. Essentially I have an h1 html tag with class "me" and a button with class "poo". The first click works and my css color changes, however the second click does not work?
$(".poo").click(function(e){
e.preventDefault();
$(".me").css("color","green");
var haha = $("<button>Click Me!!!</button>");
$(this).after(haha);
$(haha).addClass("changer");
$(this).hide();
});
$(".changer").click(function(e){
e.preventDefault();
$(".me").css("color","black");
$(this).hide();
});
Bind the second click to the parent element:
$(document).on('click', '.changer', function() {
//function here
});
The changer click handler is bound before the element exists. Try using the $.on method instead.
http://api.jquery.com/on/
$('body').on('click', '.changer', function() {...})
This works because the event handler is bound to the document body, which already exists on the page. When there is a click anywhere in the body, jQuery will check if the clicked element matches the selector .changer and execute the callback if so.
Alternatively, you could just bind the $('.changer').click event within the first callback.
Update fiddle: http://jsfiddle.net/0yodg7gb/7/
$(".poo").click(function(e){
e.preventDefault();
$(".me").css("color","green");
var haha = $("<button>Click Me!!!</button>").addClass('changer');
$(this).after(haha);
$(haha).addClass("changer");
$(this).hide();
bindClick();
});
function bindClick(){
$(".changer").bind('click',function(e){
e.preventDefault();
$(".me").css("color","black");
$(this).hide();
});
}

Prevent click on another button jquery

How to prevent click another button if first is clicked...
Example
http://jsfiddle.net/C5AVH/3/
$(function(){
$('.vote_like').one('click',function(){
$('.vote_dislike').removeClass('vote_dislike');
alert('Done!')
});
$('.vote_dislike').one('click',function(){
$('.vote_like').removeClass('vote_like');
alert('Done!');
});
});
Like -
Dislike
When you click Like button i want disable click on Dislike button and inversely...
im try with removing class but seems that not working...
$('.vote_like').removeClass('vote_like');
You can remove the click handler
$(function () {
$('.vote_like').one('click.like', function () {
$('.vote_dislike').off('click.like');
console.log('like!')
});
$('.vote_dislike').one('click.like', function () {
$('.vote_like').off('click.like');
console.log('dislike!');
});
});
Demo: Fiddle
Because you've attached the .one handler to each button, it will still be executed at most one time according to the jquery docs. To prevent the click you must remove the handler after one is clicked.
$('.vote_like').one('click',function(){
$('.vote_dislike').off();
alert('Done!')
});
$('.vote_dislike').one('click',function(){
$('.vote_like').off();
alert('Done!');
});
});
Like -
Dislike
But better yet, why not just attach the one handler to both elements and check which was clicked:
$(function(){
$('.vote_like,.vote_dislike').one('click',function(){
if($(this).is('.vote_like')){
//set data for like
}
else{
//set data for dislike
}
//make ajax call
});
Anchors don't have a way to disable them, so you'd either need to remove the anchor or set a boolean in your javascript to track if it's been clicked.
Or, you can convert them into actual button elements, play with the disabled state.
Or you can use jquery to add custom data attributes to the anchor to track if it's "disabled"
Demo
$(function(){
$('.vote_like, .vote_dislike').on('click',function(){
$(this).siblings('.vote_like, .vote_dislike').add($(this)).prop('disabled',true);
if ($(this).hasClass('vote_like')) {
/* Do like things */ alert('like');
}else{
/* Do dislike things */ alert('dislike');
}
});
});
Can use one handler for both buttons and remove click handler within it for both
var btns=$('.vote_like, .vote_dislike').on('click',function(e){
e.preventDefault();
var isLikeBtn=$(this).is('.vote_like');
/* remove click handler for both, remove class from other button */
btns.off('click').not(this).removeClass( isLikeBtn ? 'vote_dislike' : 'vote_like');
});
Since using off on both would be equivalent of using one

Button click event based on class isn't being fired on button that is dynamically created.

I have a table with dynamically created rows. Each row has a link button that you click on to delete that row. This is the click function here:
$(".deleteButton").on('click', function(){
console.log("Delete Hit");
var successful = deleteEntry($(this).attr('id'));
if(successful == true){
$(this).parent().parent().remove();
}else{
alert("Delete Unsuccessful.");
}
});
Some of the buttons are created with one function when the page first loads. Those work, but this other function seems to create a button with the right classes for the event to fire. It creates a link like this.
<a class="deleteButton dButton" href="#">
while the one that works right creates a link like this,
<a href='#' class='deleteButton'>
I have checked in the inspector and it says that the button has the class deleteButton, which is required to fire the event, but it seems to be ignoring it entirely. The Delete Hit never shows in the console.This has really confused me for some time, and I'd appreciate the help anyone can give.
You need to use delegated events for elements that doesn't exist on DOM when you bind event handler
$(document).on('click', '.deleteButton', function(){...}
Where document can be any .deleteButton container that exists at handler bind time.
You can delegate your events.
$(document).on('click', '.deleteButton', function(e){
//do something
});
here is a similar post where I explain the differences between bind live and "on".
How Jquery/Javascript behave on dynamic content updation?
The existing buttons get their event handlers on page load, but the new button is added to the DOM afterwards. You would have to update your JavaScript code, like this:
$(document).on('click', '.deleteButton', function(){
console.log("Delete Hit");
var successful = deleteEntry($(this).attr('id'));
if(successful == true){
$(this).parent().parent().remove();
}else{
alert("Delete Unsuccessful.");
}
});
Find more info in the jQuery docs at http://api.jquery.com/on/#direct-and-delegated-events.

Categories

Resources