jQuery Trigger Click not work at first click - javascript

I have a trouble with jquery trigger click. I need to play audio from audio tag via trigger click. When i click first time on first element it work, but if I click in another element, the first click not work. If i click 2nd time it will be work.
var Audioplaying = false;
jQuery('.playAudio').click(function(e) {
var playerID = jQuery(this).next('.audioPlayer').attr('id');
var playerBTN = jQuery(this);
if (Audioplaying == false) {
Audioplaying = true;
jQuery("#"+playerID)[0].play();
playerBTN.addClass('play');
} else {
Audioplaying = false;
jQuery("#"+playerID)[0].pause();
playerBTN.removeClass('play');
}
e.preventDefault();
});

The variable Audioplaying is shared, it is not unique so you probably want it to be unique per element. So use data() to keep track of the state for each player.
jQuery('.playAudio').click(function(e) {
var player = jQuery(this).next('.audioPlayer');
var playerID = player.attr('id');
var playerState = player.data('isPlaying') || false; // get if it is running
player.data('isPlaying', !playerState); // update the boolean
var playerBTN = jQuery(this);
if (!playerState) {
jQuery("#"+playerID)[0].play();
playerBTN.addClass('play');
} else {
jQuery("#"+playerID)[0].pause();
playerBTN.removeClass('play');
}
e.preventDefault();
});

Maintain the state of each button separately. so, you can use an object with it's 'id' as the key.
example : { button_id : true/false }
var Audioplaying = {};
jQuery('.playAudio').click(function(e) {
var playerID = jQuery(this).next('.audioPlayer').attr('id');
var playerBTN = jQuery(this);
if (!Audioplaying[playerID]) {
Audioplaying[playerID] = true; // every button has it's own state maintained in the object.
jQuery("#"+playerID)[0].play();
playerBTN.addClass('play');
} else {
Audioplaying[playerID] = false;
jQuery("#"+playerID)[0].pause();
playerBTN.removeClass('play');
}
e.preventDefault();
});
Hope it helps you arrive at a optimal solution.

Related

How do I change the name of the button and save it when reloading the page with javascript

I have a page with a button that when I click on it it changes but if I reload the page it returns as it is without changing
html
<button onload="form1.reset();" class="button" id="movetool10" onclick="movetool10();stoptool10()">حجز</button>
javascript
var clickCounter10 = 0;
var movetool10 = document.getElementById('movetool10')
movetool10.onclick = function() {
clickCounter10++;
if (clickCounter10 ===2) {
clickCounter10 = 0;
document.getElementById('movetool10').innerHTML = 'click !';
}
else {
document.getElementById('movetool10').innerHTML = 'click me';
}
};
You can make use of localStorage, save the last counter value there and fetch it in the begining, if it exists, use it. Otherwise, initialize the counter with 0 for first time render (or someone clears the localStorage). Please note that this is only on client side, so if the user clears the localStorage, the counter will be reinitialised.
Right now, the button shows up from its last state. It is toggling between the two states, you can change the logic however you want, but this is how you can make use of localStorage.
JSFiddle
var clickCounter10 = window.localStorage.getItem('clickCounter10') || 0;
var movetool10 = document.getElementById('movetool10');
changeBtn();
movetool10.onclick = function() {
clickCounter10++;
window.localStorage.setItem('clickCounter10', clickCounter10);
changeBtn();
};
function changeBtn() {
clickCounter10 = parseInt(clickCounter10, 10);
if (clickCounter10 === 2) {
clickCounter10 = 0;
document.getElementById('movetool10').innerHTML = 'click !';
} else if(clickCounter10 !== 0) {
document.getElementById('movetool10').innerHTML = 'click me';
}
}

Java Script function link combine issue in my case

I have issue in flask project, i need set up two js with one link if both was clicked or checked.
For example my data table do changes if clicked check box or selected from multi select some options.
But need make them both if selected and clicked (can be only selected or only just clicked). But need make and option for both
For make issue more clearly after get checked send value in the python function.
I think problem with url.
My js code.
// MULTISELECT
$('.selectpicker').on('change', function() {
selectedServices = $(this).val();
alert(selectedServices)
var url = '/api/VERSION/DATABALE/get?groupFilter='+ selectedServices
console.log('new URL'+url);
table.ajax.url(url).load();
table.ajax.reload();
});
// CHECK BOX
$('input[name="checkboxGroup1"]').on("click", function(){
console.log("Filter clicked")
var own = false;
var own = false;
// var id = parseInt($(this).val(), 10);
if($('#own').is(":checked")) { var f_own = true;}
else { var f_own = false; }
if($('#research').is(":checked")) { var f_research = true;}
else { var f_research = false; }
var url = '/api/VERSION/DATABALE/get?f_own='+ f_own +'&f_research='+ f_research
console.log('new URL'+url);
table.ajax.url(url).load();
table.ajax.reload();
});
So need somehow combine this js. IF only selected options send this selectedServices if checked checkbox send only values from checkbox js. IF selected or clicked both send both values.
I try combine like this
$('.selectpicker').on('change'); or ('input[name="checkboxGroup1"]').on("click", function(){
selectedServices = $(this).val();
console.log("Filter clicked")
var own = false;
var research = false;
if($('#own').is(":checked")) { var f_own = true;}
else { var f_own = false; }
if($('#research').is(":checked")) { var f_research = true;}
else { var f_research = false; }
alert(selectedServices)
var url = '/api/VERSION/DATABALE/get?groupFilter='+ selectedServices + '&f_own='+ f_own +'&f_research='+ f_research
console.log('new URL'+url);
table.ajax.url(url).load();
table.ajax.reload();
});
I dont getting any error, but it not change date in my datatable too, when i combine my js code
Any idea how to solve it? all help will be appreciated

append to div one time

I am revisiting this code I made a year ago with the help of another person. Unfortunately I don't have contact with them anymore to get more help. Basically It dynamically adds classs to the tb and b nodes of a document coming from namesToChange. Now what I am trying to do is append some text to the div with class dtxt node but still use this code below. I am using the code $('td.pn_adm_jeff').children('div.dtxt').append('zzz'); and it works but it constantly appends more than once as seen in the photo below. How do I go about making it add once and stop?
Photo
http://img6.imageshack.us/img6/5392/7c23ddb145954aefadb1b9f.png
Code
function customizefields(a) {
$('td b').each(function () {
name = $(this).text();
if (name.indexOf(" ") != -1) {
name = name.substring(0, name.indexOf(" "))
}
if (a[name]) {
this.className = a[name].class;
this.parentNode.className = a[name].img
}
})
$('td.pn_adm_jeff').children('div.dtxt').append('zzz');
}
var namesToChange = {
'Jeff' :{'class':'pn_adm','img':'pn_adm_jeff'}
};
setInterval(function () {
customizefields(namesToChange)
}, 1000);
Update
var needsUpdate = true;
function customizefields(a) {
$('td b').each(function () {
name = $(this).text();
if (name.indexOf(" ") != -1) {
name = name.substring(0, name.indexOf(" "));
}
if (a[name]) {
this.className = a[name].class;
this.parentNode.className = a[name].img;
}
});
if (needsUpdate) {
$('td.pn_adm_jeff').children('div.dtxt').append('testing');
needsUpdate = false;
}
}
var namesToChange = {
'jeff' :{'class':'pn_adm','img':'pn_adm_jeff'};
};
setTimeout(function () {
customizefields(namesToChange);
}, 1000);
use setTimeout rather than setInterval (interval is for repeating a timer task, timeout is a single timer task)
To prevent a certain task from occuring more than once in a repeated task, there is a simple fix.
// global variable
var needsUpdate = true;
// now in the timer task
if (needsUpdate) {
$('td.pn_adm_jeff').children('div.dtxt').append('zzz');
needsUpdate = false;
}
Does that work for you?
Define a global variable to hold the input flag
var appended = false;
function appendthestring() {
if(!appended) $('td.pn_adm_jeff').children('div.dtxt').append('zzz');
appended = true;
}

Toggling two events on one button

I'm trying to add some functionality to be able to edit comments inline. So far it's pretty close, but I'm experiencing issues trying to trigger a second event. It works the first time, but after that, fails.
$(function() {
var $editBtn = $('.js-edit-comment-btn');
var clicked = false;
$editBtn.on('click', $editBtn, function() {
clicked = true;
var $that = $(this);
var $form = $that.closest('.js-edit-comment');
var $commentTextBody = $that.closest('div').find('.js-comment-body');
var commentText = $commentTextBody.text();
var $editableText = $('<textarea />');
if ($that.text() === 'Save Edits') {
$that.text('Saving...').attr('disabled', true);
} else {
$that.text('Save Edits').attr('alt', 'Save your edits');
}
// Replace div with textarea, and populate it with the comment text
var makeDivTextarea = function($editableText, commentText, $commentTextBody) {
$editableText.val(commentText);
$commentTextBody.replaceWith($editableText);
$editableText.addClass('gray_textarea js-edited-comment').width('100%').css('padding', '4px').focus();
};
makeDivTextarea($editableText, commentText, $commentTextBody);
var saveEdits = function($that, $editableText) {
$that.on('click', $that, function() {
if (clicked) {
var comment = $that.closest('div').find('.js-edited-comment').val();
$editableText.wrap('<div class="js-comment-body" />').replaceWith(comment);
$that.text('Edit').attr('alt', 'Edit Your Comment').attr('disabled', false);
$('#output').append('saved');
clicked = false;
return false;
}
});
};
saveEdits($that, $editableText);
return false;
});
});​
jsfiddle demo here
Hiya demo for your working solution: http://jsfiddle.net/8P6uz/
clicked=true was the issue :)) I have rectified another small thing. i.e. $('#output') is set to empty before appending another saved hence text **saved** will only appear once.
small note: If I may suggest use Id of the button or if there are many edit buttons try using this which you already i reckon; I will see if I can write this more cleaner but that will be sometime latter-ish but this should fix your issue. :) enjoy!
Jquery Code
$(function() {
var $editBtn = $('.js-edit-comment-btn');
var clicked = false;
$editBtn.on('click', $editBtn, function() {
clicked = true;
var $that = $(this);
var $form = $that.closest('.js-edit-comment');
var $commentTextBody = $that.closest('div').find('.js-comment-body');
var commentText = $commentTextBody.text();
var $editableText = $('<textarea />');
if ($that.text() === 'Save Edits') {
$that.text('Saving...').attr('disabled', true);
} else {
$that.text('Save Edits').attr('alt', 'Save your edits');
}
// Replace div with textarea, and populate it with the comment text
var makeDivTextarea = function($editableText, commentText, $commentTextBody) {
$editableText.val(commentText);
$commentTextBody.replaceWith($editableText);
$editableText.addClass('gray_textarea js-edited-comment').width('100%').css('padding', '4px').focus();
};
makeDivTextarea($editableText, commentText, $commentTextBody);
var saveEdits = function($that, $editableText) {
$that.on('click', $that, function() {
if (clicked) {
var comment = $that.closest('div').find('.js-edited-comment').val();
$editableText.wrap('<div class="js-comment-body" />').replaceWith(comment);
$that.text('Edit').attr('alt', 'Edit Your Comment').attr('disabled', false);
$('#output').text("");
$('#output').append('saved');
clicked = true;
return false;
}
});
};
saveEdits($that, $editableText);
return false;
});
});​

How to detect if some text box is changed via external script?

I have some jQuery plugin that changes some elements, i need some event or jQuery plugin that trigger an event when some text input value changed.
I've downloaded jquery.textchange plugin, it is a good plugin but doesn't detect changes via external source.
#MSS -- Alright, this is a kludge but it works:
When I call boxWatcher() I set the value to 3,000 but you'd need to do it much more often, like maybe 100 or 300.
http://jsfiddle.net/N9zBA/8/
var theOldContent = $('#theID').val().trim();
var theNewContent = "";
function boxWatcher(milSecondsBetweenChecks) {
var theLoop = setInterval(function() {
theNewContent = $('#theID').val().trim();
if (theOldContent == theNewContent) {
return; //no change
}
clearInterval(theLoop);//stop looping
handleContentChange();
}, milSecondsBetweenChecks);
};
function handleContentChange() {
alert('content has changed');
//restart boxWatcher
theOldContent = theNewContent;//reset theOldContent
boxWatcher(3000);//3000 is about 3 seconds
}
function buttonClick() {
$('#theID').value = 'asd;lfikjasd;fkj';
}
$(document).ready(function() {
boxWatcher(3000);
})
try to set the old value into a global variable then fire onkeypress event on your text input and compare between old and new values of it. some thing like that
var oldvlaue = $('#myInput').val();
$('#myInput').keyup(function(){
if(oldvlaue!=$('#myInput').val().trim())
{
alert('text has been changed');
}
});
you test this example here
Edit
try to add an EventListner to your text input, I don't know more about it but you can check this Post it may help
Thanks to #Darin because of his/her solution I've marked as the answer, but i have made some small jQuery plugin to achieve the same work named 'txtChgMon'.
(function ($) {
$.fn.txtChgMon = function (func) {
var res = this.each(function () {
txts[0] = { t: this, f: func, oldT: $(this).val(), newT: '' };
});
if (!watchStarted) {
boxWatcher(200);
}
return res;
};
})(jQuery);
var txts = [];
var watchStarted = false;
function boxWatcher(milSecondsBetweenChecks) {
watchStarted = true;
var theLoop = setInterval(function () {
for (var i = 0; i < txts.length; i++) {
txts[i].newT = $(txts[i].t).val();
if (txts[i].newT == txts[i].oldT) {
return; //no change
}
clearInterval(theLoop); //stop looping
txts[i].f(txts[i], txts[i].oldT, txts[i].newT);
txts[i].oldT = $(txts[i].t).val();
boxWatcher(milSecondsBetweenChecks);
return;
}
}, milSecondsBetweenChecks);
}

Categories