How to prevent click event on second times on a button - javascript

I have few buttons, when I click on those buttons some divs are creating automatically, but here I need to prevent to create any div when I click on next time on the same button on which I already clicked.
Code is below
HTML
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="details">
<button id="append">button1</button>
<button id="append">button2</button>
<button id="append">button3</button>
<div id="parent"></div>
</div>
SCRIPT
(function(){
var count = 0;
$('button').click(function(){
$('#parent').append('<div id="first'+count+'">text</div>');
count++;
});
});

Use the .one() method. This binds a handler that only runs once for each element.
$(function() {
var count = 0;
$('button').one("click", function() {
$('#parent').append('<div id="first' + count + '">text</div>');
count++;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="details">
<button id="append">button1</button> <button id="append">button2</button> <button id="append">button3</button>
<div id="parent"></div>
</div>

Basic idea is creating click flag.
Flag is set to true once clicked and set to false if action is finished.
The action should be performed only if flag is false.
Like this:
(function(){
var count = 0;
var flag = false;
$('button').click(function(){
if(flag) return false; // Disable when action is on
// Action starts
flag = true;
$('#parent').append('<div id="first'+count+'">text</div>');
count++;
// Action ends
flag = false;
});
});

Here are three possible solutions:
Disable the button that was clicked by adding $(this).attr('disabled',true); inside anonymous click function.
Adding a data-enabled attribute to the buttons and checking it. Your HTML for a button becomes like this: <button id="append" data-enabled="true">button1</button> and then you add this to the anonymous click function:
(function(){
var count = 0;
$('button').click(function(){
if ( $(this).data('enabled') == 'false' ) return;
else
{
$(this).data('enabled', 'false');
$('#parent').append('<div id="first'+count+'">text</div>');
count++;
}
});
});
Create an array that with the button as keys and their enabled/disabled boolean value as their value and refer to that in the anonymous click function.

1- Your code needs a $ in first of your js to calling it after document.ready: $(function(){...}), or adding () at end of it for calling Immediately ((function(){...})();).
2- You can use off to remove a listener from an element.
other things is ok in your code. please look at result:
$(function(){
var count = 0;
$('button').click(function(){
$('#parent').append('<div id="first'+count+'">text</div>');
count++;
$(this).off("click");//One of benefits of this way is: you can add some conditions for removing this event. > if(...) $(this).off("click");
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="details">
<button id="append">button1</button> <button id="append">button2</button> <button id="append">button3</button>
<div id="parent"></div>
</div>

Just unbind it after first click.
$(function(){
var count = 0;
$('button').click(function(){
count = Number($(this).data('click')||0);
if(count>0){
$(this).unbind("click");
}
count = count+1;
$(this).data('click',count);
$('#parent').append('<div id="first'+count+'">text</div>');
});
});

Related

Jquery - Stop Event of Other Class

This is what I want
Jquery:
$("body").on('click','.js-validate-url',function(){
var url = $(".url").val();
if(url==""){
// STOP WORKING OF .js-loader click
// I want if url is empty it should not alert
}else{
//OK
// and here it should work fine
// it should alert
}
});
$("body").on('click','.js-loader',function(){
alert();
});
HTML
<form>
<input class="url">
<button class="js-loader js-validate-url"></button>
</form>
<form>
<button class="js-loader"></button>
</form>
Why I am doing this
Upper class is different for all buttons
But loader class is same for all buttons it shows loader inside clicked button
I found
e.stopPopagation();
But that works if I use it in loader click callback But I want to stop when button is clicked and url is empty
Cannot check url=="" inside loader click call back cause it is same for all button i dont want to check on other buttons click too so checking for single button
I would recommend using classes to check for condition.
$("body").on('click','.js-loader',function(){
var _this = $(this)
if(_this.hasClass('js-loader') && _this.hasClass('js-validate-url')){
// if both classes js-loader, js-validate-url are present on button
alert()
}else{
alert("js-loader") // if only js-loader present on button
}
});
I'm not sure if I understand what you are trying to do, but I guess you can merge your events into a single one and use an external function only when it met a condition.
You could also use removeEventListener but I don't believe you need it for your problem.
var myFunction = function(){
alert('loader');
};
$("body").on('click','.js-validate-url',function(){
var url = $(".url").val();
if (url){ alert('validate: '+url); }
else myFunction();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" value="google.com" class="url"/>
<button class="js-validate-url js-loader">Bt1</button>
<button class="js-loader">Bt2</button>
This is what I did and is working fine as per my requirement
$("body").on('click','.js-validate-url',function(){
var url = $(".url").val();
if(url==""){
// STOP WORKING OF .js-loader click
// I want if url is empty it should not alert
}else{
$(this).removeClass("js-diable");
//OK
// and here it should work fine
// it should alert
}
});
$("body").on('click','.js-loader',function(){
if($(this).hasClass('js-scud-disabled')){
//NOTHING TO DO
}else{
alert();
}
});
HTML
<form>
<input class="url">
<button class="js-loader js-validate-url js-disable"></button>
</form>
<form>
<button class="js-loader"></button>
</form>
$("body").on('click','.js-loader',function(){
if($(this).hasClass('js-loader js-validate-url')){
alert();
} else {
if(url==""){
} else {
}
}
});

show an element only if contentEditable div is changed

$('#story').on('keypress', function(){
$('#btnsave').show();
});
#story{
background:gold;
min-height:54px;
padding:9px;
}
#btnsave{
display:none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='story' contentEditable='true'>lorem ipsum</div>
<br>
<button id='btnsave'>SAVE</div>
I need to show btnsave only if story is changed.
kyedown and keyup don't work because of funcional and other keys included.
keypress seems to be ok, except backspace and delete - when pressing - nothing happens.
What to do?
Change
$('#story').on('keypress', function(){
$('#btnsave').show();
});
To
document.getElementById("story").addEventListener("input", function() {
$('#btnsave').show();
}, false);
OR
$('#story').on('input', (e) => {
$('#btnsave').show();
});
Working Demo: https://codepen.io/OtakunityJL/pen/vVOvxV
as comment above you need to change keypress to input, and if you want to show only #btnsave when it different with previous content save original content as variable, then compare.
var oldContent = $('#story').text();
var myTimeout;
$('#story').on('input', function() {
clearTimeout(myTimeout);
myTimeout = setTimeout(function() {
if ($('#story').text() != oldContent) {
$('#btnsave').show();
}
else{
$('#btnsave').hide();
}
}, 200)
});
$('#btnsave').on('click', function(){
oldContent = $('#story').text();
$('#btnsave').hide();
})
#story{
background:gold;
min-height:54px;
padding:9px;
}
#btnsave{
display:none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='story' contentEditable='true'>lorem ipsum</div>
<br>
<button id='btnsave'>SAVE</div>
you can store the contents to a variable and check if it is different after blur() event. If it is different, then it changed. http://jsfiddle.net/maxofpower/a4QNB/850/
another scenario is that user maybe press key but doesn't change anything...
var content = $('#story').html();
$('#story').blur(function() {
if (content!=$(this).html()){
alert('change() called.');
content = $(this).html();
}
});
To handle this kind is issue, you can trigger an event handler when the div with attribute contenteditable set to true loose the focus. Which can be done by setting an event handler on the blur event. The other way is to set a timer which wait a certain number of second in which a user doesn't type any thing on they keybord and manualy trigger disable the contenteditable and set the display property of the button to block
var story = document.querySelector('#story');
var btn = document.querySelector('#btnsave');
story.addEventListener('blur', function(event){
btn.style.display = "block";
});
#btnsave {
display: none;
}
#story{
background:gold;
min-height:54px;
padding:9px;
}
<div id='story' contentEditable='true'>lorem ipsum</div>
<br>
<button id='btnsave'>SAVE</div>

Use off() inside event jquery

$(function(){
$("#selector").on("someevent", function(){
let variable = some_value;
$("#anotherselector").click(function(){
//code involving variable here
if(condition){
$(this).off(reference to click event here);
}
});
});
});
Is there any way to turn off an event from inside its handler? I'm trying to do something like the code above, and I need it to turn off ONLY that specific click event (each click event is different).
To reference the click event, you can simply pass it 'click' and the selector for which to disable the event:
$(function(){
$("#selector").on("someevent", function(){
$("#anotherselector").click(function(){
if(condition){
$('#anotherselector').off('click');
}
});
});
});
let numHandler = 0;
$('#register').click(function () {
let counter = 0;
let num = ++numHandler;
$('#clickme').click(function handler () {
counter++;
console.log(`Handler ${num} clicked!`);
if (counter == 3) $('#clickme').off('click', handler);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="clickme">Click me!</button>
<button id="register">Register new handler</button>
You can read more about the off function in the jQuery documentation.

JQuery/JS function not firing on <a>

I have five slide shows on one page and I want to be able to cycle through all of them. The slideshow is made of an UL with each a different ID, so I want to create two functions for the arrows to cycle through the slides. And I want to pass the slide ID. My code:
$(document).ready(function() {
var slides = document.querySelectorAll('#slides li');
var slidesTotal = $('#slides li').length;
var currentSlide = 1;
function nextSlide() {
//$('a.nextSlideArrow').click(function() {
$('#slides .slide' + currentSlide).hide();
currentSlide++;
if(currentSlide > slidesTotal) {
currentSlide = 1;
}
$('#slides .slide' + currentSlide).show();
//return false;
//});
}
function previousSlide() {
//$('a.previousSlideArrow').click(function() {
$('#slides .slide' + currentSlide).hide();
currentSlide--;
if(currentSlide == 0) {
currentSlide = slidesTotal;
}
$('#slides .slide' + currentSlide).show();
//return false;
//});
}
});
<div id="slider-container">
<ul id="slides">
<?php
for ($i = 1; $i <= $amountImagesSlideshow[3]; $i++) {
echo '<li class="slide'.$i.'"><img src="'.$directories[3],$i.'.jpg" /></li>';
}
?>
</ul>
<div class="galleryPreviewArrows">
❮
❯
</div>
</div>
Now the funny thing is, if I remove the comments where the click is on the jQuery object and comment out the function, it will work. But not this way? I don't understand.
There is a difference between onclick event and functionality of href attribute.
When you write like this:
❮
It means, you are hyper referencing(trying to redirect) to some location whenever this anchor tag is clicked.
It doesn't mean you are doing only click action. It means, you are doing click + redirection.
href = click + redirection.
whereas, your need is only click event handling. Therefore, how you are handling through jquery.
$('a').on("click",function(){
----
----
})
This will work fine.
You shouldn't be using href to try to access a javascript function. That attribute is for navigation purposes. Also, binding to a jquery click even is the better way to handle your events so you adhere to separation of concerns design patterns.
If you need to put your function call in an attribute decorator, use the onclick attribute instead and don't evaluate the function by adding the parenthesis, just reference it.
<a onclick="previousSlide" class="previousSlideArrow">❮</a>
Anchor tag is for navigation which requires Href attribute. You should not use href for event handling. Instead:
<div class="galleryPreviewArrows">
❮
❯
</div>
It is strange..But writing that function outside document.ready works. It looks like that function should be defined before document is ready.
That may be the reson alert works always..which is a built-in function.
Also this is not the recommended way to bind event listner. Use jquery on/off to add/remove listners.
function nextSlide() {
//$('a.nextSlideArrow').click(function() {
alert('next');
//return false;
//});
}
function previousSlide() {
//$('a.previousSlideArrow').click(function() {
alert('prev');
//return false;
//});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="slider-container">
<div class="galleryPreviewArrows">
❮
❯
</div>
</div>

Javascript Dynamic Event Handling, Not Jquery

here is my code
<html>
<head>
<script type="text/javascript">
window.onload = function(){
sel = document.getElementsByTagName('select');
for(i=0;i<sel.length;i++)sel[i].onclick = function(){alert('');}
}
</script>
</head>
<body>
<div id="ss"></div>
<select></select>
<input type="button" onclick="document.getElementById('ss').appendChild(document.createElement('select'))"/>
</body>
</html>
"onclick" event working for static tag "Select" but not working for Dynamically created "Select". In other word i want to know what is alternate to .live of JQuery in Javascript.
Bind the event to a parent element, that already exists in the DOM:
document.body.addEventListener('click', function (e) {
if (e.target.tagName.toLowerCase() == 'select') {
alert('You clicked a select!');
}
});
JS Fiddle demo.
It would be slightly more sensible to bind the click to an element 'closer' to the form, and if you use getElementById() rather than getElementByTagName() it's more simple, since you don't have to worry about the index of the number you're binding to.
jQuery's live function works by using "Event Delegation". The basic idea is that you bind a listener on a parent element, which is guaranteed to exist when the page loads. Any element below that (with the exception of some) will fire off an event which can be caught by the parent listener. From there you would need to retrieve the target/sourceElement of the event and determine whether or not it's one you care about.
Something like this will work for listening to clicks. Just make sure that any new elements you are adding are located within the proper parent container and have an attribute which distinguishes them from the rest of the clickable elements.
<html>
<head>
<script type="text/javascript">
window.onload = function(){
// get the relevant container
var eventContainer = document.getElementById("EventContainer");
// bind a click listener to that container
eventContainer.onclick = function(e){
// get the event
e = e || window.event;
// get the target
var target = e.target || e.srcElement;
// should we listen to the click on this element?
if(target.getAttribute("rel") == 'click-listen')
{
alert("You clicked something you are listening to!");
}// if
};
};
</script>
</head>
<body>
<div id="EventContainer">
<input type="button" rel="click-listen" name="myButton" value="Listening to this button." />
<input type="button" name="anotherButton" value="Not listening." />
<p>I'm also listening to this a element: listening to this</p>
</div>
</body>
</html>
there's no need to bind the onclick handler to every select every time you add one.
I am not going to retype your whole page, but you'll see what's going on by reading following snippets:
function handler() {
alert('You clicked a select!');
}
window.onload = function(){
sel = document.getElementsByTagName('select');
for(int i= 0; i < sel.length; i++) {
sel[i].onclick = handler;
}
}
function addSelect() {
var slt = document.createElement("select");
document.getElementById('ss').appendChild(slt);
slt.onclick = handler;
}
<input type="button" onclick="addSelect();"/>
You're only setting the onclick when the window loads. All you need to do is put the code currently in the window.onload into a named function, then call it every time you add a new select.
here's the dumb way to do it:
<html>
<head>
<script type="text/javascript">
function update () {
sel = document.getElementsByTagName('select');
for(i=0;i<sel.length;i++)sel[i].onclick = function(){alert('');}
}
window.onload = update;
</script>
</head>
<body>
<div id="ss"></div>
<select></select>
<input type="button" onclick="document.getElementById('ss').appendChild(document.createElement('select'));update();"/>
</body>
</html>
You can use a cross-browser solution as shown below to add event handler dynamically
sel = document.getElementsByTagName('select');
for( i=0; i<sel.length; i++){
if (sel[i].addEventListener){
sel[i].addEventListener("click", clickHandler, false);
} else if (sel[i].attachEvent){
sel[i].attachEvent("onclick", clickHandler);
}else{
sel[i].onclick = clickHandler;
}
}
function clickHandler(event){
}

Categories