How to disable this button for 5 sec after first click? - javascript

In my code the button .getmore gets clicked on scroll down. It loads data from database.Works fine. I need to make it disable for 5 sec after every click. How can I set this delay timer?
Or is it possible to disable this function for 5 sec once it fires? Disable the button or disable the function anything will work for me.
$(window).scroll(function(){
if ($(document).height() <= $(window).scrollTop() + $(window).height()) {
// Here how can i set a delay time of 5 sec before next click
$('.getmore').click();
}
});

You can use setTimeout() function of jQuery.
$('.getmore').prop('disabled', true);
setTimeout(function() {
$('.getmore').prop('disabled', false);
}, 5000);

One solution is to use setTimout and disable the button with javascript using document.getElementById("yourButtonID").disabled = true;

You could use a flag inside the clickHandler:
var clickHandler = () => {
if (clickHandler.running)
return
clickHandler.running = true
setTimeout(() => { clickHandler.running = false }, 5000)
console.log(new Date())
}
$('#getmore').click(clickHandler)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='getmore'>more</div>

U can use setTimeout() n after that, put ur disable button function inside it.
setTimeout(document.getElementById('ur_button_id').style.display = 'none', 500);

Related

How to remove a class with delay after a button is pressed?

I have a full page navigation on my website. To make sure the page can't scroll when the navigation is opened, the body get's the 'no-scroll' class with overflow hidden. This also removes the scrollbar when the nav is opened.
When the nav button is pressed again and the nav closes, the class 'no-scroll' is removed from the body, revealing the scrollbar immediately. The navbar takes 1.05s to fully close. What I tried to achieve is to have the class 'no-scroll' not be removed immediately, but with a delay. Is there any way to do this?
This is the code I currently have to add and remove the class on button click:
<script>
// when DOM is ready
document.addEventListener('DOMContentLoaded', () => {
// on .nav-menu-button click
document.querySelectorAll('.nav-menu-button').forEach(trigger => {
trigger.addEventListener('click', function(){
this.x = ((this.x || 0) + 1)%2;
if(this.x){ // 1st click
document.querySelectorAll('body').forEach(target => target.classList.add('no-scroll'));
}
else{ // 2nd click (toggle)
document.querySelectorAll('body').forEach(target => target.classList.remove('no-scroll'));
}
});
});
});
</script>
Thanks in advance!
You could use setTimeout function. Here I've used 5 seconds delay:
setTimeout(function(){
document.querySelectorAll('body').forEach(target => target.classList.remove('no-scroll'));
},5000);
You can use setTimeout Function from WebAPI which helps in such cases. It registers approximate(minimum) timeout (in milliseconds, your case is 1050), after which specified function will be executed. In the end code will look like this:
setTimeout(() => {
document.querySelectorAll('body').forEach(
(target) => target.classList.remove('no-scroll')
);
}, 1050);
The code from Ann Francis solved it!
<script>
// when DOM is ready
document.addEventListener('DOMContentLoaded', () => {
// on .nav-menu-button click
document.querySelectorAll('.nav-menu-button').forEach(trigger => {
trigger.addEventListener('click', function(){
this.x = ((this.x || 0) + 1)%2;
if(this.x){ // 1st click
document.querySelectorAll('body').forEach(target => target.classList.add('no-scroll'));
}
else{ // 2nd click (toggle)
setTimeout(function(){
document.querySelectorAll('body').forEach(target => target.classList.remove('no-scroll'));
},900);
}
});
});
});
</script>
You should try .add() and .remove() instead of classList.add() and classList.remove():
document.querySelectorAll('body').forEach(target => target.remove('no-scroll'));

Disable a button when the one button is pressed, enable after 5 seconds

I have 2 button that load some data, each button take some time to load. so i want to disable the other button for like 10 seconds or until the other button finish rendering.
when one button is clicked, the other button should be disabled for 5 seconds and reenabled after that. how can i do that?
$(function() {
var clicked = false;
var first = $('#but1');
var second = $('#but2');
first.on('click', function() {
clicked = !clicked;
if (clicked)
second.attr('disabled', 'enabled');
else
second.removeAttr('disabled');
});
second.on('click', function() {
clicked = !clicked;
if (clicked)
first.attr('disabled', 'enabled');
else
first.removeAttr('disabled');
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="but1">but1</button>
<button id="but2">but2</button>
You can actually make it relative and avoid id's by grouping the buttons. Though, this is just academic. If you're actually waiting for data to load, you should wait until the data is loaded before enabling the button - which is easy enough if you show that code.
$(function() {
$('.toggles button').click(function() {
$('.toggles button').not(this).attr('disabled', 'disabled')
setTimeout(() => {
$('.toggles button').removeAttr('disabled');
}, 5000)
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='toggles'>
<button id="but1"> button 1</button>
<button id="but2"> button 2</button>
</div>
Consider the following example.
$(function() {
var first = $('#but1');
var second = $('#but2');
first.click(function() {
if (!second.prop("disabled")) {
second.prop('disabled', true);
setTimeout(function() {
second.prop("disabled", false);
}, (10 * 1000));
}
});
second.click(function() {
if (!first.prop("disabled")) {
first.prop('disabled', true);
setTimeout(function() {
first.prop("disabled", false);
}, (10 * 1000));
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="but1">but1</button>
<button id="but2">but2</button>
You want to use .prop() to manage element properties such as disabled. Please see: https://api.jquery.com/prop/
You can also use setTimeout() to execute a code snippet after a specific amount of time has passed. See more: https://www.w3schools.com/jsref/met_win_settimeout.asp

How to keep view changes after refresh page?

In my MVC application i have a view in which i refresh the page each 10 seconds.
I have some paragraph in the view are hidden and a button which make those paragraphs not hidden.
The problem that when i click on the button to make the paragraph show when the page reload automatically in 10 seconds returns the paragraph hidden.
This is the button:
<button id="button">Display Internal Sequences</button>
This is the paragraph :
<p1 hidden style="text-align:center;font-size: 50px; padding:-25px; margin:-25px;">#Html.Label(#Model.CSLine.ModuleOrderInternalSequence > long.MinValue ? #Model.CSLine.ModuleOrderInternalSequence.ToString() : string.Empty)</p1>
This is the script to make the p not hidden:
<script>
$(document).ready(function () {
$("#button").click(function () {
$("p1").attr("hidden", false);
var show ='true';
localStorage.setItem(key, show);
});
});
</script>
This is the reload each 10 seconds:
setTimeout(function () {
window.location.reload(1);
}, 10000);
$(document).ready(function() {
var show = localStorage.getItem(key);
if (show == 'true')
{
$("p1").attr("hidden", false);
} })
The result is that the paragraph returns hidden after each reload.
I want when i click the button the paragraph became not hidden even after reload.
Thank you
Try https://jsfiddle.net/hbmk7e2L/
Note: Your page will only reload after 10 seconds in this case and will only refresh once.
If you want the page to refresh every 10 seconds, you should use setInterval instead of setTimeout.
<script>
$(document).ready(function() {
// If you want the page to refresh constantly, you should use setInterval intead of setTimeout. setTimeout fires only once.
setTimeout(function () {
window.location.reload(1);
}, 10000);
$("#button").click(function() {
$("p1").attr("hidden", false);
localStorage.setItem("show_p1", true);
});
if (localStorage.getItem("show_p1") == 'true') {
$("p1").attr("hidden", false);
}
});
</script>
<p1 hidden style="text-align:center;font-size: 50px; padding:-25px; margin:-25px;">#Html.Label(#Model.CSLine.ModuleOrderInternalSequence > long.MinValue ? #Model.CSLine.ModuleOrderInternalSequence.ToString() : string.Empty)</p1>
<button id="button">Display Internal Sequences</button>
if (show = 'true')
This is not a comparison, you are setting the value of "show" to "true". Use == to compare values.
Try using jQuery's prop() method instead of attr() like so:
$("p1").prop("hidden", false);
The jQuery documentation for prop() describes the difference between the two methods, especially for boolean attributes like hidden. Also, here is a post regarding this .prop() vs.attr()

How to trigger if statement jQuery

I have a quick question. I am trying to trigger an event when two 'container' divs no longer have any divs inside them.
My Script so far is as follows:
if (($('#Summary2 div').length) + ($('#Summary3 div').length)) == 0) {
alert("hello");
}
My problem is -how do I get this piece of code to trigger? I think what happens is that it gets read once and then sits there idle as nothing triggers it.
Kind regards and thank you,
G
I would suggest you to check for div on specific time let us say every 1 hour then you can use setinterval as shown below :-
setInterval(
function(){
if ($('#Summary2 div').length + $('#Summary3 div').length == 0) {
alert("hello");
}
}, 60 * 60 * 1000);
Try this code. On "remove" event may trigger.
$("#Summary2 div, #Summary3 div").on("remove", function () {
if (($('#Summary2 div').length) + ($('#Summary3 div').length)) == 0) {
alert("hello");
}
});

Prevent 'click' event from firing multiple times + issue with fading

Morning folks. Have an issue with a simple jQuery gallery i'm making. It lets the user cycle through a collection of images via some buttons and at the same time, rotates through these images on a timer. My problem is that the user is able to click the button multiple times which queues up the fade in animation and repeats it over and over, e.g. user clicks button 5 times > same image fades in/out 5 times > gallery moves to next image.
I've tried using:
$('#homeGalleryImage li a').unbind('click');
After the click event is fired and then rebinding:
$('#homeGalleryImage li a').bind('click');
After it's done but this simply removes the click event after pressing a button once and never rebinds to it?
I've also tried disabling the button via:
$('#homeGalleryImage li a').attr('disabled', true);
To no avail... ?
There is a secondary issue where if you manage to click a button while the image is in a transition, the next image appears 'faded' as if the opacity has been lowered? Very strange... Here is the code for button clicks:
var i = 1;
var timerVal = 3000;
$(function () {
$("#homeGalleryControls li a").click(function () {
var image = $(this).data('image');
$('#galleryImage').fadeOut(0, function () {
$('#galleryImage').attr("src", image);
});
$('#galleryImage').fadeIn('slow');
$('.galleryButton').attr("src", "/Content/Images/Design/btn_default.gif");
$(this).find('img').attr("src", "/Content/Images/Design/btn_checked.gif");
i = $(this).data('index') + 1;
if (i == 4) {
i = 0;
}
timerVal = 0;
});
});
Here is the code that cycles through the images on a timer:
//Cycle through gallery images on a timer
window.setInterval(swapImage, timerVal);
function swapImage() {
$('#galleryImage').fadeOut(0, function () {
var imgArray = ["/Content/Images/Design/gallery placeholder.jpg", "/Content/Images/Design/1.jpg", "/Content/Images/Design/2.jpg", "/Content/Images/Design/3.jpg"];
var image = imgArray[i];
i++;
if (i == 4) {
i = 0;
}
$('#galleryImage').attr("src", image);
$('#galleryImage').fadeIn('slow');
});
var currentButton = $('#homeGalleryControls li a img').get(i - 1);
$('.galleryButton').attr("src", "/Content/Images/Design/btn_default.gif");
$(currentButton).attr("src", "/Content/Images/Design/btn_checked.gif");
}
I realise it might be a better idea to use a plugin but I'm very new to jQuery and I'd like to learn something rather than using some ready made code.
Any help at all, is much appreciated.
Thankyou
You could always try adding something to the element to cancel the click event?
For example
$(".element").click(function(e) {
if ( $(this).hasClass("unclickable") ) {
e.preventDefault();
} else {
$(this).addClass("unclickable");
//Your code continues here
//Remember to remove the unclickable class when you want it to run again.
}
}):
In your case you could try adding a check on the click.
$('#homeGalleryImage li a').attr('data-disabled', "disabled");
Then inside your click event
if ( $(this).attr("data-disabled" == "disabled") {
e.preventDefault();
} else {
//Ready to go here
}
Edit
Here is a working example showing the element becoming unclickable. http://jsfiddle.net/FmyFS/2/
if you want to make sure that the registered event is fired only once, you should use jQuery's one :
.one( events [, data ], handler ) Returns: jQuery
Description: Attach a handler to an event for the elements. The handler is executed at most once per element per event type.
see examples:
using jQuery: https://codepen.io/loicjaouen/pen/RwweLVx
// add an even listener that will run only once
$("#click_here_button").one("click", once_callback);
using vanilly JS: https://codepen.io/loicjaouen/pen/gOOBXYq
// add a listener that run only once
button.addEventListener('click', once_callback, {capture: true, once: true});

Categories

Resources