jquery onclick runs twice - javascript

I have the following javascript when my script is loaded:
var current_selected_note = $('#new_note');
current_selected_note.addClass('hover active');
$('#note-item-lists').on('click', '.list-group-item', function () {
//removes the hover color from the previous selected
current_selected_note.removeClass('hover active');
// sets the currently selected equal to the selected note
current_selected_note = $(this);
// adds the hover active to the currently selected
current_selected_note.addClass('hover active');
//adds the title of the currently selected to the title input field
$('#txt_new_note_title').val($(this).find('Strong').text());
selected_note_id = $(this).get(0).id;
getNote(selected_note_id);
load_comments(selected_note_id);
});
$( "#note-item-lists").find('li').first().trigger( "click" );
Now AFTER this is loaded i click one of my buttons which has the following javascript:
$('#note-item-lists').on('click','.close',function(){
var r = confirm('Are you sure you wish to delete "'+$(this).next('div').find('.new_note_title').text()+'" ?')
if(r == true){
deleteNote($(this));
$( "#note-item-lists").find('li').first().click();
}
})
function deleteNote(button){
var id = button.closest('li').get(0).id;
$.ajax({
type: 'POST',
url: '/solo/ajax_delete',
dataType: 'json',
data: {
id: id
},
success: function (data) {
}
});
button.closest('li').remove();
}
When this happens (i debug it) and the event function is called first 1 time (adding the class correctly) but is then happens immediatly again.
Anyone tried this before?

Try this, It will call one time.
$('#note-item-lists .close').on('click',function(){
alert("Hello");
});

Try using .off()
$('#note-item-lists').on('click', '.list-group-item', function () {
$(this).off(); //add this here

Related

how to get value outside jquery click function

I have a on click function to get the id of a,and I want to alert it.
The following code is not working showing null, why? thanks
var projectId=null;
$('body').on('click', '#list a', function(){
projectId=this.id; //id should = 30
alert(projectId); //here display 30
});
alert(projectId); //here display null
what i really want to do is :
a.js I have sth like, when I click "a" it redirect to another page which need to render by my projectId:href='/projectDetail' this page call b.js
$.ajax({
type: "GET",
url: 'http://xxx',
dataType:'json',
contentType:"application/json",
success:function(data){
console.log(data);
var projectList="<ul style='list-style:none;'>"
for (var i = 0; i < data.data.length; i++) {
projectList += "<li><div id='listall'><a
id='"+data.data[i].projectId+"'
href='/projectDetail'>"+
"<img class='back' src='/img/Homepage_ProjectFrame.png'></li>"
}
var projectList="<ul>"
});
var projectId=null;
$(document).on('click', '#listall a', function (){
event.preventDefault();
projectId=this.id;
alert(projectId);
});
alert(projectId);
b.js I have:
$.ajax({
type: "GET",
url: 'http://xxx?projectId='+projectId
dataType:'json',
contentType:"application/json",
success:function(data){
console.log(data.data);
$(".photoprojectD").attr("src",data.data.projectPhotoUrl);
$(".dlocation p").html(data.data.countryName);
$(".dcategory p").html(data.data.categoryName);
});
So i need projectId from a.js to render dynamic information
Do you have any good ideas?
Thanks a lot for your guys helping
the second alert(projectId); outside the "click" event handler runs as soon as the page loads. Inevitably this is before your "click" handler can possibly be executed, because the user has likely not had time to click on it, and even if they had time, there's no guarantee that they will. Therefore the variable projectId is not populated when that code executes.
You can certainly use projectId outside your "click" event, but you have to wait until after at least one "click" event has happened before you can expect it to have a value.
There's also danger that your hyperlinks are causing the page to postback before any of this ever happens. Since you're using jQuery you can prevent this very easily:
$('body').on('click', '#list a', function(event) {
event.preventDefault(); //prevent default hyperlink redirect/reload behaviour
projectId=this.id; //id should = 30
alert(projectId); //here display 30
});
Lastly, ensure that this other place you want to use the value is not doing anything silly like declaring another "projectId" variable with narrower scope and then trying to use that. For example, this will not work as you wish:
var projectId = null;
$('body').on('click', '#list a', function(event) {
event.preventDefault(); //prevent default hyperlink redirect/reload behaviour
projectId=this.id; //id should = 30
alert(projectId); //here display 30
exampleFunc(); //call the function below
});
function exampleFunc() {
var projectId = null; //oops, another "projectId" with narrower scope (within this function) will take precedence here
alert(projectId); //will be null
});
Whereas this will:
var projectId = null;
$('body').on('click', '#list a', function(event) {
event.preventDefault(); //prevent default hyperlink redirect/reload behaviour
projectId=this.id; //id should = 30
alert(projectId); //here display 30
exampleFunc(); //call the function below
});
function exampleFunc() {
alert(projectId); //will be 30
}

Jquery timeout for doubleclick

I have a clickable div which should first present a text instruction to tap again in order to fire ajax action, which is under a new class name added after a 1st click. This text has a timeout and will change back to the original.
The problem is that once the text is back to original the actual ajax fire action should stop working as well, but the actual class is not removed. Any suggestions?
What I really need is a kind of doubleclick with a 2second timeout..
function onlyfire() {
$(".onlyfire").click(function() {
var div = $(this);
var original = $(this).html();
div.html("Tap again");
$(".onlyfire").addClass("fire");
setTimeout(function() {
$(div).html(original);
$(".onlyfire").removeClass("fire");
}, 2000);
$(".fire").click(function(fire) {
$.ajax({
type: "POST",
data: dataString,
url: "something.php",
cache: false,
success: function(html) {
div.html(html);
}
});
});
return false;
});
};
<div class="onlyfire">
Do Something
</div>
here is the jsfiddle:
https://jsfiddle.net/jngqzw7q/1/
You could just use an if statement inside the click handler to see whether it is the first or second click (by checking the class), and perform the appropriate action:
function onlyfire() {
$('.onlyfire').click(function() {
var div = $(this);
if (div.is('.fire')) { // second click
alert("this is showing only when the text is 'Tap again'");
} else { // first click
var original = $(this).html();
div.text("Tap again");
div.addClass("fire").removeClass('.onlyfire');
setTimeout(function(){
$(div).html(original);
$(".onlyfire").removeClass("fire");
}, 2000);
}
return false;
});
};
onlyfire();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="onlyfire">
Do Something
</div>
Note: Setting a click handler inside an event handler for another click is not always that good an idea.
You can use .one() with event namespace as parameter, .off() referencing event namespace
function handleClick(e) {
var div = $(this).data("original", this.innerHTML);
// var original = div.html();
div.html("Tap again");
$(".onlyfire").off("click").addClass("fire");
// http://stackoverflow.com/questions/39057179/why-is-click-event-attached-to-classname-fired-after-classname-is-removed#comment65464000_39057261
var fire = $(".fire");
fire.one("click.fire", function() {
alert("this should not be showing once the text is changed back to original");
});
setTimeout(function() {
fire.off("click.fire");
div.removeClass("fire")
.html(div.data("original")).click(handleClick);
}, 2000);
}
function onlyfire() {
$(".onlyfire").click(handleClick);
};
onlyfire();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<div class="onlyfire">
Do Something
</div>

Catching focus on a jQueryUI menu item with a listener broader than a click listener

I've defined a jQueryUI menu with id leftmenu and on its list elements, I have defined a function on clicking one item, as follows:
$('#leftmenu>li').click(function () {
var clickedId = this.id;
$.ajax({
type: "POST",
cache: false,
url: "/Session/Index/",
success: function (result) {
if (result.length > 0)
{
performListItemAction(clickedId);
}
else
{
window.location.href = '/Home/Index/'
}
}
});
});
This works fine, but now I want to change it so that instead of the click on the menu item, I want to capture focus and selection on that item in a more general way, such as using the keyboard. Currently, I can navigate through the menu using the up and down keys on the keyboard, but the inner code does not get called. I know this is because it is only supposed to happen on click, but the same thing happpened when I tried activate and focus in place of the click as well.
How can I get it to perform the same behavior as click in a more general way that captures selection and enter of the menu item?
Thank you.
This should be done in the select event. This way it catches both click or select from focused keyboard actions.
Example: https://jsfiddle.net/Twisty/v671x6ns/
jQuery
$(function() {
$('#leftmenu').menu({
select: function(e, ui) {
var selectId = ui.item.attr("id");
$.ajax({
type: "POST",
cache: false,
url: "/Session/Index/",
success: function(result) {
if (result.length > 0) {
performListItemAction(selectId);
} else {
window.location.href = '/Home/Index/'
}
}
});
console.log(e.type + " event, ID: " + selectId);
}
});
});

AJAX jQuery on click dynamically created only works first time

I am trying to create a dropdown menu that I dynamically insert into using jQuery. The objects I'm inserting are notifications, so I want to be able to mark them as read when I click them.
I have an AJAX call that refreshes the notifications every second from the Django backend.
Once it's been refreshed, I insert the notifications into the menu.
I keep an array of the notifications so that I don't create duplicate elements. I insert the elements by using .append(), then I use the .on() method to add a click event to the <li> element.
Once the click event is initiated, I call a function to .remove() the element and make an AJAX call to Django to mark the notification as read.
Now my problem:
The first AJAX call to mark a notification as read always works. But any call after that does not until I refresh the page. I keep a slug value to identify the different notifications.
Every call I make before the refresh uses the first slug value. I can't figure out why the slug value is tied to the first element I mark as read.
Also, if anyone has a better idea on how to approach this, please share.
Here's my code:
var seen = [];
function removeNotification(elem, urlDelete) {
elem.remove();
console.log("element removed");
$.ajax({
url: urlDelete,
type: 'get',
success: function(data) {
console.log("marked as read");
},
failure: function(data) {
console.log('failure to mark as read');
}
});
}
function insertNotifications(data) {
for (var i = 0; i < data.unread_list.length; i++) {
var slug = data.unread_list[i].slug
var urlDelete = data.unread_list[i].url_delete;
if (seen.indexOf(slug) === -1) {
var elem = $('#live-notify-list').append("<li id='notification" +
i + "' > " + data.unread_list[i].description + " </li>");
var parent = $('#notification' + i).wrap("<a href='#'></a>").parent();
seen.push(slug);
$( document ).ready(function() {
$( document ).on("click", "#notification" + i, function() {
console.log("onclick " + slug);
removeNotification(parent[0], urlDelete);
});
});
}
}
}
function refreshNotifications() {
$.ajax({
url: "{% url 'notifications:live_unread_notification_list' %}",
type: 'get',
success: function(data) {
console.log("success");
insertNotifications(data);
},
failure: function(data) {
console.log('failure');
}
});
}
setInterval(refreshNotifications, 1000);
I really don't know what do you mean with parent[0] in
removeNotification(parent[0], urlDelete);
I think you can simply try $(this)
removeNotification($(this), urlDelete);
but to be honest I find to put
$( document ).ready(function() {
$( document ).on("click", "#notification" + i, function() {
console.log("onclick " + slug);
removeNotification(parent[0], urlDelete);
});
});
inside a loop .. its bad thing try to put it outside a function and use it like
$( document ).ready(function() {
setInterval(refreshNotifications, 1000);
$( document ).on("click", "[id^='notification']", function() {
console.log("onclick " + slug);
removeNotification($(this), urlDelete);
});
});
and try to find a way to pass a urlDelete which I think it will be just one url

hide a dynamically created element with jquery

I am getting data through ajax.I have an array holding all the data.Now I am running a loop through the array and dynamically creating a 'p' and a 'button' corresponding to each element of the array.If I click the button the innerHTML of corresponding 'p' should be passed to ajax and the button must disappear.Here is the sample of what i tried:
<script>
for(var i=0;i<foo.length;i++)
{
addElement(foo[i],i);
}
function addElement(foo,i)
{
ni=document.getElementById("asdf");
new_but=document.createElement('input');
new_p=document.createElement('p');
new_p.id='text'+toString(i);
new_p.innerHTML=foo;
new_but.type='button';
new_but.value='add';
new_but.id=toString(i);
new_but.className='but';
ni.appendChild(new_p);
ni.appendChild(new_but);
}
$(document).ready(function(){
$('.but').each(function(){
$(this).click(function(){
$.ajax({
type:'POST',
data:'awdwad',
url:'aadwewq.php',
success:function(result)
{
if(result==no_error)
$(this).hide();
}
});});});});
</script>
The elements are created but I am unable to access them later using their ids or classes with jquery.
The problem is because the click handler is being assigned onload, when the .but element does not exist. You need to delegate the click handler to the parent element like this:
$(document).ready(function(){
$('#asdf').on('click', '.but', function(){
$.ajax({
type:'POST',
data:'awdwad',
url:'aadwewq.php',
success:function(result) {
if (result == no_error)
$(this).hide();
}
});
});
});
Also, you can shorten your addElement function using jQuery like this:
function addElement(foo, i) {
var $ni = $('#asdf');
var $p = $('<p></p>', { 'id', 'text' + toString(i) }).html(foo).appendTo($ni);
var $button = $('<input></input>', {
'type': 'button',
'id': toString(i),
'class': 'but'
}).appendTo($ni);
}
Use .on and attach event on some parent object or document. Also there is no need to iterate over objects.
$(document).on("click", ".but", function(){
});
this inside your success callback of your $.ajax call refers to the ajax call itself.
You should make a reference to the button first.
With the feedback of the other answers combined:
$(function() {
$(document).on('click', '.but', function() {
var btn = $(this);
$.ajax({
type:'POST',
data:'awdwad',
url:'aadwewq.php',
success:function(result)
{
if(result==no_error)
$(btn).hide();
}
});
});
});
function addElement(foo,i){
ni=document.getElementById("asdf");
new_but=document.createElement('input');
new_p=document.createElement('p');
new_p.id='text'+i; //remove toString
new_p.innerHTML=foo;
new_but.type='button';
new_but.value='add';
new_but.id=i; // remove toString
new_but.className='but';
ni.appendChild(new_p);
ni.appendChild(new_but);
}

Categories