i am trying to do post AJAX request only once after color is set for more than 2 seconds.
[DEMO FIDDLE]
fiddle
in the fiddle i want AJAX call to be fire only once after color is selected.
i don't want AJAX call to done on every click
how to do that?
As you want it to fire only once, bind .one() instead of .on() to the element. This will make the event execute only once.
And for delay, use setTimeout().
You can simply add a flag to check if your code ran before.
var timeout;
var executed;
var arry = ['red', 'blue','orange', 'green'], i=0, len= arry.length;
$('#element').on('click',function(){
$(this).css('background',arry[i++]);
if(i===len){i=0;}
if(!executed){
clearTimeout(timeout);
timeout = setTimeout(function(){
alert("executed");
executed = 1;
}, 2000);
}
})
#element{
width:50px;
height:50px;
border:1px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="element"></div>
Demo
This can be done by just adding a condition in your click event as below
$(document).on("click", "#element", function () {
if ($('body').data("isServerHit") === undefined) {
$('body').data("isServerHit", true);
setTimeout(function () {
// Write the code for ajax call here
alert('server will hit now');
}, 2000);
}
});
For more details on $('body').data("isServerHit", true);, visit save data (in jquery)
Hope this helps :)
Related
I need to trigger a window.open function on the click of body, but only if the click is after few seconds.
EXAMPLE:- if the second click is done immediately, it shouldn't open the window. but after 5 seconds, if the click is made, the window should open.
My code isn't working.
<script>
setInterval(myadFunction,5000);
function myadFunction()
{
$("body").click(function () {
window.open("https://www.google.com");
});
}
</script>
This is a wordpress website., and I entered this code before <body> tag.
Why isn't it working?
You can use a flag to simulate what you want. In this case "canClick" flag will do the job for you.Reset it back to true after your desired timeout.
var canClick = true;
$("body").click(function () {
if (canClick) {
window.open("https://www.google.com");
canClick = false;
setTimeout(() => {
canClick = true
}, 5000);
}
});
Let me know if you face any issue with this snippet.
You could try something like:
<button onclick="timeFunction()">Submit</button>
<script>
function timeFunction() {
setTimeout(function(){ window.open("https://www.google.com"); }, 5000);
}
</script>
It consists of this:
setTimeout(functionname, milliseconds, arg1, arg2, arg3...)
The following are the parameters −
functionname − The function name for the function to be executed.
milliseconds − The number of milliseconds.
arg1, arg2, arg3: These are the arguments passed to the function.
First of all. You should make sure that you are placing the code in the right place. Since it's Wordpress. That bugger really get on my nerves. Try putting it in the active theme.
var click_allowed = 0; //global var (you use const if supported)
setTimeout(function(){ click_allowed = 1; },5000);
jQuery('body').click(function(){
if(click_allowed) window.open("https://www.google.com");
});
jQuery has been used instead of $ for the selectors due to wordpress native jquery limitation.
you can use settimeout(function, millisecond)
I'm making a kind of note system for my users in Laravel application.
I want this textarea that the user writes their notes on to be saved after the user is done typing, instead of running the ajax call on every change done because that would be a lot of requests.
What is the best way to achieve this?
Should I use some sort of timer here to determine if the user is done writing?
Currently I'm just using the following:
notesTextarea.on('change', function(e) {
$.ajax({ ... });
});
While the other proposed solutions (on blur or on keydown if it's the enter key), would work, I think they're not what you're looking for.
What if the user neither clicks outside the textarea, nor uses enter? I would use a technique called debounce instead. You can read about it for example here: https://davidwalsh.name/javascript-debounce-function or see an example here: https://www.geeksforgeeks.org/debouncing-in-javascript/
The short version is, it only calls a function after an event has stopped firing for a given length of time.
Add the debounce function to your code by either using an NPM package (ex. https://www.npmjs.com/package/debounce) or directly adding the necessary code:
// Returns a function, that, as long as it continues to be invoked, will not
// be triggered. The function will be called after it stops being called for
// N milliseconds. If `immediate` is passed, trigger the function on the
// leading edge, instead of the trailing.
function debounce(func, wait, immediate) {
var timeout;
return function() {
var context = this, args = arguments;
var later = function() {
timeout = null;
if (!immediate) func.apply(context, args);
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) func.apply(context, args);
};
};
Source: https://davidwalsh.name/javascript-debounce-function which has taken it from Underscore.js
Then have a function doing your ajax calls like:
var makeAjaxCall = function(e) {
$.ajax({ ... });
};
Now you can simply add a listener like:
var minTimeoutBetweenCallsInMilliSeconds = 500;
notesTextarea.on('change', debounce(makeAjaxCall, minTimeoutBetweenCallsInMilliSeconds));
Now the makeAjaxCall function would be called only 500ms after the last change event occurred, a.k.a. the user stopped typing.
You can use the onlbur event instead. It happens when the element lost the focus, that could means you are no longer changing its content:
$("#notesTextarea").on('blur', function(e) {
// $.ajax({ ... });
console.log("has finished, content to be saved:" + $(this).val());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>
Notes: <textarea id="notesTextarea"></textarea>
</p>
<p>
Other something: <input type="text">
</p>
One way, you can make the call on pressing the enter key on keydown event:
notesTextarea.on('keydown', function(e) {
if(e.keyCode == 13){
$.ajax({ ... });
}
});
You can also think of blur which will occur when the element loses focus
notesTextarea.on('blur', function(e) {
$.ajax({ ... });
});
If you want to automate this saving you can call to ajax, after N number of characters typed by user each time.
Otherwise, you can call to ajax function on CTRL+S key combination
document.addEventListener('keydown', function(event) {
if (event.ctrlKey && event.key == 's') {
event.preventDefault(); //prevent default file save box open by browser
alert('ajax call goes here!');
}
});
Similar to #Mamun's answer.
Call Ajax on keypress event:
$("textarea").on('keypress', function() {
//$.ajax({ ... });
console.log('request sent!');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>
<textarea id="textarea"></textarea>
</p>
I have this code:
document.getElementById('auth-button').addEventListener('click', authorize);
When my page load I want to trigger that without clicking the button.
This is my view
When authorized button clicked this is the output
I want to auto click that button when my page load.
You can use addEventListener to the DOMContentLoaded event:
document.addEventListener('DOMContentLoaded', function() {
authButton.click();
}, false);
Full example:
https://jsfiddle.net/7q0gxehk/1/
you can use Document ready in jQuery, try this..
$( document ).ready(function() {
authorize();
});
or this in javaScript..
window.onload = authorize;
NOTE: The load event fires at the end of the document loading process. At this point, all of the objects in the document are in the DOM, and all the images, scripts, links and sub-frames have finished loading.
You could call the function authorize() on load of page using below code :
document.addEventListener("DOMContentLoaded", function(event) {
authorize();
});
You can register authorize as handler to be called when the page is fully loaded:
$(document).ready(authorize);
This requires jQuery. The same can be achieved without jQuery this way:
window.addEventListener('load', authorize);
It would be easier to tigger authorize function directly on page load using window.onload which is better than document.onload, see window.onload vs document.onload
window.onload = authorize;
However, if you are thinking about triggering click programmatically which is not suggested since it won't work properly across browsers e.g. Safari doesn't work at all
None of the other answers offered thus far seem to take something into account - that the registered handler may in fact need to be aware of it's place in the DOM.
We could for instance, have a number of buttons that all call the same handler, with that handler manipulating the surrounding DOM. Simply calling authorize when the page loads will not be sufficient.
I've chosen to use DIVs instead of BUTTONs to demonstrate that the .click() method still works.
A far better way is to actually click the button, using javascript.
#1 Not working
function byId(id){return document.getElementById(id)}
function allByClass(clss){return document.getElementsByClassName(clss)}
// useful for HtmlCollection, NodeList, String types
function forEach(array, callback, scope){for (var i=0,n=array.length; i<n; i++)callback.call(scope, array[i], i, array);} // passes back stuff we need
window.addEventListener('load', onDocLoaded, false);
function onDocLoaded(evt)
{
forEach(allByClass('mBtn'), addHandler);
function addHandler(elem)
{
elem.addEventListener('click', authorize, false);
}
alert('hit a okay to call authorize');
authorize(); // wont return from this call, since authorize relies on a valid 'this' value
}
function authorize(evt)
{
this.classList.add('clicked');
this.textContent = 'clicked';
}
.mBtn
{
border: solid 1px #555;
border-radius: 2px;
display: inline-block;
}
.clicked
{
color: #dddddd;
pointer-events: none;
}
<div class='mBtn'>Try me</div><div id='btn2' class='mBtn'>Or me</div><div class='mBtn'>Or even, me</div>
#2 - Does work
function byId(id){return document.getElementById(id)}
function allByClass(clss){return document.getElementsByClassName(clss)}
// useful for HtmlCollection, NodeList, String types
function forEach(array, callback, scope){for (var i=0,n=array.length; i<n; i++)callback.call(scope, array[i], i, array);} // passes back stuff we need
window.addEventListener('load', onDocLoaded, false);
function onDocLoaded(evt)
{
forEach(allByClass('mBtn'), addHandler);
function addHandler(elem)
{
elem.addEventListener('click', authorize, false);
}
alert('hit okay to click the 2nd button with javascript');
byId('btn2').click(); // will return from this call, since authorize relies on a valid 'this' value, and the btn gives it one.
}
function authorize(evt)
{
this.classList.add('clicked');
this.textContent = 'clicked';
}
.mBtn
{
border: solid 1px #555;
border-radius: 2px;
display: inline-block;
}
.clicked
{
color: #dddddd;
pointer-events: none;
}
<div class='mBtn'>Try me</div><div id='btn2' class='mBtn'>Or me</div><div class='mBtn'>Or even, me</div>
Use one of the following:
<body onload="script();">
or
document.onload = function ...
or
window.onload = function ...
I would like pause on hover when the mouse hovers over the fadelinks div for this script:
$(function(){
$('.fadelinks > :gt(0)').hide();
setInterval(function(){$('.fadelinks > :first-child').fadeOut().next().fadeIn().end().appendTo
('.fadelinks');}, 5000);
});
The html is along the lines of:
<div class="fadelinks">
<div>...</div>
<div>...</div>
</div>
I've tried a few things relating to interval to try and cram pause on hover functionality in there, but with my extremely limited jquery knowledge, everything I've tried breaks the script, leaving it stuck on the last slide or the first slide. Would just like this simple script to pause on mouse-hover and start up again on mouse-exit.
Here's a JSFiddle of the script in its natural state.
Try using .hover() , declaring variable to reference setInterval , using a function to call setInterval
$(function(){
// define `_interval` variable
var _interval;
// cache `.fadelinks` element
var elem = $(".fadelinks");
elem.find("> :gt(0)").hide();
elem.hover(function() {
// "pause" at `hover` of `.fadelinks`
clearInterval(_interval)
}, function() {
// "reset"
interval()
});
var interval = function() {
_interval = setInterval(function(){
elem.find("> :first-child")
.fadeOut().next().fadeIn().end()
.appendTo(elem);
}, 2000)
};
interval()
});
jsfiddle https://jsfiddle.net/ccmgdfog/4/
In your case, there wasn't the need for jQuery. Only with stopInterval you can control it. Altrough there is the jQuery $.stop() function, we wouldn't get the desired result.
I've changed a bit your code:
$(function(){
$('.fadelinks > :gt(0)').hide();
var interval = setInterval(intervalFunc, 2000);
$('.fadelinks').on('mouseenter',function(){
clearInterval(interval);
});
$('.fadelinks').on('mouseout',function(){
interval = setInterval(intervalFunc, 2000);
});
function intervalFunc(){
$('.fadelinks > :first-child').fadeOut().next().fadeIn().end().appendTo('.fadelinks');
}
});
script
$(document).ready(function () {
var meter_id = $("#MeterReadingTypes li a.link_active").attr("id");
var range_id = $("#DateRangeTypes li a.link_active").attr("id");
window.setInterval(PostMainChartValues(meter_id, range_id), 5000);
...
});
function PostMainChartValues(meter_id, range_type_id) {
$.ajax({
...
});
}
window.setInterval is not trigerred. If I write an alert in setInterval it works. What is the reason of this? Why function is not triggering? I tracked it with chrome DevTools, and there is no move.
The first parameter to setInterval should be a function (or an evalable string). Right now, you are calling PostMainChartValues() and passing its return value to setInterval().
Change it to:
window.setInterval(function() {
PostMainChartValues(meter_id, range_id);
}, 5000);
This is not an ajax issue. You are using in wrong mode the setInterval parameter.
Create an anonymous function like bellow:
window.setInterval(function () { PostMainChartValues(meter_id, range_id); }, 5000);