Toggling two events on one button - javascript

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

Related

How to mark as selected the default text of multiple textarea on tabindex?

I have few textarea on which I want to get the default text selected when I tabbing upon it.
For a single textarea I've found a script which I adapted to my situation but is not an elegant solution.
How can I shorten it.
<script type="text/javascript">
var textBox1 = document.getElementById("textarea_1");
var textBox2 = document.getElementById("textarea_2");
var textBox3 = document.getElementById("textarea_3");
textBox1.onfocus = function() {
textBox1.select();
// Work around Chrome's little problem
textBox1.onmouseup = function() {
// Prevent further mouseup intervention
textBox1.onmouseup = null;
return false;
};
};
textBox2.onfocus = function() {
textBox2.select();
textBox2.onmouseup = function() {
textBox2.onmouseup = null;
return false;
};
};
textBox3.onfocus = function() {
textBox3.select();
textBox3.onmouseup = function() {
textBox3.onmouseup = null;
return false;
};
};
</script>
You can add a dedicated class name and refactor the code to be more generic using class name as selector an make it work for multiple textareas like this:
// Add the class 'auto-selectable' to the desired <texarea/> elements
var textBoxes = document.getElementByClassName('auto-selectable');
for(var i = 0; i < textBoxes.length; i++) {
var textBox = textBoxes[i];
textBox.select();
// Work around Chrome's little problem
textBox.onmouseup = function() {
// Prevent further mouseup intervention
textBox.onmouseup = null;
return false;
};
}
a small correction to Plamen's answer: Elements not Element
var textBoxes = document.getElementsByClassName('auto-selectable');
instead of:
var textBoxes = document.getElementByClassName('auto-selectable');

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

jQuery Trigger Click not work at first click

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.

jQuery click inside each loop

I want to loop my click events, to make the code shorter. I might have 30 of these values later on.
My working code
$(document).ready(function () {
var last_click = '';
$("#title").click(function() { last_click = 'title'; });
$("#subtitle").click(function() { last_click = 'subtitle'; });
$("#test").click(function() { last_click = 'test'; });
});
This is how I want it (not working)
My guess is that the each-loop runs on dom ready and then never again and that way the click-event can never be triggered?
$(document).ready(function () {
var last_click = '';
var contents = new Array();
contents = ['title', 'subtitle', 'test'];
$.each(contents , function(index, value){
$("#" + value).click(function() { last_click = value; });
});
});
If there is not solved like I would, I would be thankful for a nice workaround.
I would rather add a class to all elements you want to bind this to, eg class="last-click"
and define the binding once as:
$(".last-click").on('click', function() {
last_click = this.id;
}
If you really wanted to make it shorter, give them all a similar class.
$(document).ready(function () {
var last_click = '';
$(".theclass").click(function() {
last_click = this.id;
});
});
if you have value attribute for your buttons or elements, you can do it:
$(document).ready(function() {
var last_click = '';
$("input").click(function() {
last_click = $(this).attr('value');
alert(last_click);
});
});​
I assumed that you are using "input type="button". Also here is the demo you can see it in action: http://jsfiddle.net/rS2Gb/5/

Toggle Mute Javascript Function with Jquery Toggle

Hi All I am trying to write both an if/else statement along with toggling an image. Basically my goal is to toggle an image (in this case with an id of soundonoff). However I can't seem to figure out where I am going wrong. The issue is the toggle works, but the detect of whether its muted or not does not work. (In my full code for example I have it switch innerHTML of various audio/video files, this is where document.getElementsByName('mymedia')[0] comes in. Any help would be tremendously appreciated I have spent about 4 hours working on this and can't seem to figure it out.
I should add that I do not know where to add an eventlistener for detectmute(), I tried to add it to my video, and to the button soundonoff but neither got working yet.
Here is my code:
function detectmute(){
if(document.getElementById('soundonoff').src == 'images/icons/soundoff.png'){
document.getElementsByName('mymedia')[0].muted = true;
}
else if(document.getElementById('soundonoff').src == 'images/icons/soundon.png'){
document.getElementsByName('mymedia')[0].muted = false;
}
$("#soundonoff").toggle(function(){
this.src = "images/icons/soundoff.png";
document.getElementsByName('mymedia')[0].muted = true;
}, function() {
this.src = "images/icons/soundon.png";
document.getElementsByName('mymedia')[0].muted = false;
});
}
Well I solved my own issue, Solution was the following:
$("#soundonoff").toggle(function(){
this.src = "images/icons/soundoff.png";
document.getElementsByName('mymedia')[0].muted = true;
$("#soundonoff").attr('name', 'soundoff');
}, function() {
this.src = "images/icons/soundon.png";
document.getElementsByName('mymedia')[0].muted = false;
$("#soundonoff").attr('name', 'soundon');
});
function detectmute(){
var soundstate = document.getElementById('soundonoff');
if (soundstate.name == "soundon")
{
document.getElementsByName('mymedia')[0].muted = false;
}
else if (soundstate.name == "soundoff")
{
document.getElementsByName('mymedia')[0].muted = true;
}
}
$('#soundonoff').on('click', function () {
var $this = $(this);
if ($this.attr('src') == 'images/icons/soundon.png') {
$this.attr('src', 'images/icons/soundoff.png').attr('data-muted', true);
} else {
$this.attr('src', 'images/icons/soundon.png').attr('data-muted', false);
}
});
Here is a demo: http://jsfiddle.net/jLvZW/3/ updated
You could also setup an object that converts one source to another:
var convert = {
'images/icons/soundon.png' : ['images/icons/soundoff.png', true],
'images/icons/soundoff.png' : ['images/icons/soundon.png', false]
};
$('#soundonoff').on('click', function () {
var $this = $(this);
$this.attr('src', convert[$this.attr('src')][0]).attr('data-muted', convert[$this.attr('src')][1]);
});
Here is a demo: http://jsfiddle.net/jLvZW/2/ Updated

Categories