jQuery call different function when buttons class has changed - javascript

I'm a little stuck on the follow issue. I have a webpage that has a button when clicked it does some ajax things and if the result/response of that is successful then the buttons class is changed.
What I then want, if that changed button is clicked again, I want it to call a different function.
The first part works no problem. The ajax is called and the buttons class is changed so the colour and text of the button is changed. But when click the button again, I want to call the .btn.off function, but it remains to call the .btn.on function while I would have hoped it would call the .btn.off function.
Unfortunately, my knowledge of jQuery is not the best, any help in the right direction would be very much appreciated.
Thank you so much.
<button type="button" class="btn on btn-danger" id="123"><i class="fa fa-trash-o"></i><span>On</span></button>
<script>
$(document).ready(function(){
$(".btn.on").click(function(){
//do some ajax stuf.....
$(this).removeClass('btn on btn-danger').addClass('btn off btn-success btn-sm');
$("span", this).text("Off");
});
$(".btn.off").click(function(){
//do some ajax stuf.....
$(this).removeClass('btn off btn-danger').addClass('btn on btn-danger btn-sm');
$("span", this).text("On");
});
});
</script>

$('.btn').click(function () {
var btn = $(this);
var isOn = btn.hasClass('on');
if (isOn) {
// do something maybe call on function or write logic for on
} else {
// do something maybe call off function or write logic for off
}
btn.toggleClass('on off'); // flip the on <-> off switch
$('span', this).text(isOn ? 'Off' : 'On'); // was on before toggle so flipped
})
You can do this by checking the classes and take action

The issue is because you're dynamically changing the classes on the element at runtime. One way to work around this is to use delegated event handlers, like this:
jQuery(function($) {
$(document).on('click', '.btn.on', function() {
// AJAX...
$(this).removeClass('on btn-danger').addClass('off btn-success btn-sm').find('span').text('Off');
});
$(document).on('click', '.btn.off', function() {
// AJAX...
$(this).removeClass('off btn-danger').addClass('on btn-danger btn-sm').find('span').text('On');
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" />
<button type="button" class="btn on btn-danger" id="123">
<i class="fa fa-trash-o"></i>
<span>On</span>
</button>

Related

How to import onClick in element with jQuery

I want to add an onclick in and a button tag over jquery
<button type="button" aria-controls="mep_0" title="Play" aria-label="Play" tabindex="0"></button>
<img id="loadingImage" src="preoader.gif" style="visibility:hidden">
I need it for this script
<script type="text/javascript">
function openImage(){
if ( document.getElementById('loadingImage').style.visibility == 'visible' )
{
document.getElementById('loadingImage').style.visibility='hidden';
} else {
document.getElementById('loadingImage').style.visibility='visible';
}}
</script>
you can add events like this:
$('#buttonid').on("click", function(){
//do something here like calling openImage();
});
you only need to give your button a unique id like this :
<button type="button" aria-controls="mep_0" title="Play" aria-label="Play" tabindex="0" id="buttonid"></button>
EDIT:
if you can not edit the button tag then you may need a different selector.
You can try to get a parent attribute to fetch the right child like this :
$('.parentclass button').on("click", function(){
//do something here like calling openImage();
});
or something like this
$('.parentclass div button').on("click", function(){
//do something here like calling openImage();
});
EDIT SOLUTION:
$(".mejs-play button").on("click", function(){
openImage();
});
You can use this code :)
$(document).ready(function(){
$("#btn").on("click", function(){
var img = $("#loadingImage");
if(img.is(":visible")) {
img.css({"display" : "none"})
} else {
img.css({"display" : "block"})
}
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button" id="btn">Click Here</button>
<img id="loadingImage" src="https://b-digital.info/wp-content/uploads/2018/09/preoader.gif">
If you can't change the html code, you can try using some of the attribute value for the selection part of the jQuery, like in next example:
$("button[title='Play']").click(function()
{
// Just for debugging on the console.
console.log("Click detected on PLAY button");
// Call the openImage() method.
openImage();
});
Your mistake here is trying to mix native js with JQuery.
When you select an item with lets say let item = document.getWhatever then you cant
use Jquery functions on this item so you have to select it from the beginning on with JQuery's method let item = $(#myItem).
Afterwards you can use Jquery functionallity to add an onclick event.
Either by setting the onclick as attribute like this:
item.attr('onclick', 'doStuff()');
or by using the .click() like so:
item.click(function() {
doStuff
});
based on your example you can add:
onClick="openImage();"
event handler on your button:
<button type="button" onClick="openImage();" aria-controls="mep_0" title="Play" aria-label="Play" tabindex="0"></button>
Try it on codepen.

jQuery Button changes not working

I'm trying to give the button a new content if it's clicked. I also add new classes. That work's perfectly fine on the first click but for some reason the innerhtml ins't changing after clicking a second time on it..
HTML:
<button class="btn btn-warning btn-invisible"><i class="fa fa-eye-slash"></i></button>
jQuery:
$('.btn-invisible').click(function() {
$(this).removeClass('btn-invisible');
$(this).addClass('btn-visible');
$(this).html('<i class="fa fa-eye"></i>');
});
$('.btn-visible').click(function() {
$(this).removeClass('btn-visible');
$(this).addClass('btn-invisible');
$(this).html('<i class="fa fa-eye-slash"></i>');
});
I got this fiddle ready: https://jsfiddle.net/dthee9w6/7/
Would love if someone could help.
You should use 'on' instead of 'click', so that you can play with dynamically added elements.
$('body').on('click','.btn-invisible',function() {
$(this).removeClass('btn-invisible');
$(this).addClass('btn-visible');
$(this).html('<i class="fa fa-eye"></i>');
});
$('body').on('click','.btn-visible',function() {
$(this).removeClass('btn-visible');
$(this).addClass('btn-invisible');
$(this).html('<i class="fa fa-eye-slash"></i>');
});
hope it helps.
Wrap your code in $(function(){}) ,which is $(document).ready(function(){
});, apart from this every thing is fine
There is no need to update the html each time on the click , all you need to do is add and remove neccessary classes.
For the first click, you are removing invisible class and what if one clicked next time, it tries to remove invisible class again which is not there, it throws an error here,you should use toggleClass
$(function() {
$('.btn-invisible').click(function() {
$(this).toggleClass('btn-invisible');
if (!$(this).hasClass('btn-visible')) {
$(this).addClass('btn-visible');
$(this).find('.fa').removeClass('fa-eye-slash').addClass('fa-eye');
}
});
$('.btn-visible').click(function() {
$(this).toggleClass('btn-visible');
if (!$(this).hasClass('btn-invisible')) {
$(this).addClass('btn-invisible');
$(this).find('.fa').removeClass('fa-eye').addClass('fa-eye-slash');
}
});
});
Hope it helps

Disable load function untill button is selected in javascript?

Hi this is an odd question and i will try to ask it correctly. I have a function using javascript called load canvas.
function loadCanvas(canvas) {
relevant code here...
}
I also have a normal button called btn.
<button class="btn" type="button">Play!</button>
I am wondering can i disable the function until the play button is selected? The function is for a game using javascript. So on load there isnt anything there until i press play then it appears!
any ideas/help please?
$(document).ready(function(){
var loadCanvas= function (canvas) {
relevant code here...
}
$("#test").on('click',loadCanvas()); // using jquery
document.getElementById("test").addEventListener("click",loadCanvas()); // using javascript
<button class="btn" id="test" type="button">Play!</button>
})
If you are having issue because other method is triggering the function you can add a flag with a boolean and turn it on when you click..
Something like that:
The button don't change at all
<button class="btn" type="button">Play!</button>
The js code with this change:
var buttonClicked = false;
function loadCanvas(canvas) {
if(buttonClicked){
relevant code here...
}
}
And in the on click function add this before call the function:
buttonClicked = true;
At the end your js should look like this:
var buttonClicked = false;
function loadCanvas(canvas) {
if(buttonClicked){
relevant code here...
}
}
$(".btn").click(function(){
buttonClicked = true;
var canvas = ...;
loadCanvas(canvas );
});
EDIT
If you have more buttons with the class .btn you should use an id and change the selector of the .click() with the selector of the id instead of the class selector
As you mentioned in the comments <script type="text/javascript"> loadCanvas("game"); </script> You are calling the function as soon as the page loads. So you will have to change it to:
<button class="btn play-button" type="button">Play!</button>
<script type="text/javascript">
$('.play-button').click(function(e){
loadCanvas("game");}
);
</script>
If you are not using jquery you will have to handle the click event by javascript.
You got to do following:
function loadCanvas(game) {
alert('loading canvas');
}
<button class="btn" type="button" onclick="loadCanvas('game')">Play!</button>

Why my plugin fires multipe callback or clicks

I am creating my simple jQuery plugin that can be use to attach for any action's confirmation. But facing very strange issue, It work fine for single element click, But when i am going to click for second element which also bind with my plugin it work fine but it's also fires for previous clicked element as well.
(function ($) {
$.fn.BootConfirm = function (options) {
// Establish our default settings
var settings = $.extend({
message: 'Are you sure about this ?',
complete: null
}, options);
var self = this;
var cointainer = '\
<div class="modal fade" id="confirmBoot" role="dialog" aria-labelledby="confirmDeleteLabel" aria-hidden="true">\
<div class="modal-dialog">\
<div class="modal-content">\
<div class="modal-header">\
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>\
<h4 class="modal-title">Confirm action</h4>\
</div>\
<div class="modal-body">\
<p>Are you sure about this ?</p>\
</div>\
<div class="modal-footer">\
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>\
<button type="button" class="btn btn-success btn-ok" id="confirm">Ok</button>\
</div>\
</div>\
</div>\
</div>';
return this.each(function () {
var self = this;
$(this).click(function () {
if (!$('#confirmBoot').length) {
$('body').append(cointainer);
}
if (settings.message) {
$('#confirmBoot').find('.modal-body').text($(this).attr('data-confirm'));
}
$('#confirmBoot').modal({ show: true });
if ($.isFunction(settings.complete)) {
$('#confirmBoot').find('.btn-ok').click(function () {
$.when(settings.complete.call(this, self)).done(function () {
$('#confirmBoot').modal("hide"); // Alerts "123"
});
});
}
});
});
}
}(jQuery));
This is my callback function :
function kaushik(myObject) {
ManageAcriveProducts(myObject);
};
and i am calling it by following way
$('a[data-confirm]').BootConfirm({
complete: kaushik
});
For more detail check this js fidder Jsfiddle. Can anyone one share possible solution or better way to do this. Or is there any better way to achieve this ?
The problem is that you're assigning a click on your btn-ok on every click event on a bootconfirmed object. And each click is linked to the object that has been clicked, so it ends up in your callback every time you click btn-ok.
One simple fix, though I'm not sure it's the best, is to remove the click on your btn-ok after the action is complete. Like this:
$.when(settings.complete.call(this, self)).done(function () {
$('#confirmBoot').modal("hide");
$('#confirmBoot').find('.btn-ok').off('click');
});
Working fiddle: http://jsfiddle.net/ywunutyw/
EDIT:
A little improvement on previous solution, it might need some adjustments, since I didn't look into details, but it should give you some ideas. To prevent adding click events and removing them every time user clicks on a button, you can define the click on modal window outside click behavior of each active/inactive button. And on click of active/inactive you define target that will be used in modal confirmation. Like this:
Just before calling behaviors with this.each:
$(document).on('click', '#confirmBoot .btn-ok',
function (e) {
if ($.isFunction(settings.complete)) {
console.log(self)
$.when(settings.complete.call(this, click_origin)).done(function () {
$('#confirmBoot').modal("hide");
});
}
});
Then on the click event of you active/inactive:
click_origin = e.target;
See fiddle: http://jsfiddle.net/ywunutyw/1/

Click issue if button has childs

I've:
backdrop = document.getElementById('backdrop');
dialog = document.getElementById('dialog');
dialog_body = document.querySelector('#dialog .body');
document.addEventListener('click', function(e) {
if ( matches.call(e.target, '[data-show=dialog]')) {
buoy.addClass(backdrop, 'fadeIn');
buoy.addClass(dialog, 'fadeIn');
var href = e.target.parentNode.getAttribute('action');
dialog_body.innerHTML = '<div>FOOOOO</div>';
[].forEach.call(document.querySelectorAll('[data-hide=dialog]'), function(el) {
el.addEventListener('click', function() {
buoy.removeClass(backdrop, 'fadeIn');
buoy.removeClass(dialog, 'fadeIn');
})
})
}
}, false);
and [data-show=dialog] is:
<button type="sumit" class="btn xs default" data-show="dialog">
<i class="ellipsis-v"></i>
</button>
If I click on
<i class="ellipsis-v"></i>
the code doesn't work..
If I click out of
<i class="ellipsis-v"></i>
the code works perfectly..
Also if I have:
<button type="sumit" class="btn xs default" data-show="dialog">
<i class="ellipsis-v"></i>
<span>fooo</span>
</button>
If I click on
<i class="ellipsis-v"></i>
or
<span>fooo</span>
the code doesn't work..
If I click out of
<i class="ellipsis-v"></i>
or
span>fooo</span>
the code works perfectly..
What is the problem?
Why Not:
function handler(e){
var t=e.target;
if(t.dataset['show']=='dialog'||t.parentNode.dataset['show']=='dialog'){
/* code ...... */
}
}
document.addEventListener('click',handler,false);
in this case you have one eventHandler.(no loops).
you can add that handler to the parentNode for simplicity.
and you have to add a better check for t.dataset['show']=='dialog' as it produces an error if it has no dataset. (i wrote it just to give you an idea)
btw you search for data-hide but you have only data-show
if you have any questions just ask..
if i misunderstood your question tell me so i can reelaborate the code.
DEMO
http://jsfiddle.net/A7xk2/1/
Less eventHadlers is always more performance...
also in this example i'm just writing now... i need alot of mouse events and most of them are on the document itself...
http://jsfiddle.net/LxX34/12/
EDIT
Add the click handler on the btn elements
it works on span on li and on button as you can see in this example.
maybe your li has some sort of preventDefault or return false??
http://jsfiddle.net/A7xk2/2/

Categories

Resources