Jquery function is starting on click but I need to stop it - javascript

I always wonder that onclick functions start to a javascript or jQuery, but How does it stop? Finally, I faced with a function in my learning progress. May you help me to find a solution?
I want to stop this function on another onclick:
function live_preview() {
var icon = document.getElementById('LivePreIcon');
if (icon.classList.contains('fa-eye-slash')) {
icon.classList.remove('fa-eye-slash');
icon.classList.add('fa-eye');
$('#result').keyup(function () {
$('#dialog').html($(this).val());
});
return;
}
if (icon.classList.contains('fa-eye')) {
icon.classList.remove('fa-eye');
icon.classList.add('fa-eye-slash');
// Stop the jquery function here
return;
}
}

var play=0;
function live_preview() {
var icon = document.getElementById('LivePreIcon');
var play;
if(!play){
if (icon.classList.contains('fa-eye-slash')) {
icon.classList.remove('fa-eye-slash');
icon.classList.add('fa-eye');
$('#result').keyup(function () {
$('#dialog').html($(this).val());
play = 1;
});
return;
}
}
else{
if (icon.classList.contains('fa-eye')) {
icon.classList.remove('fa-eye');
icon.classList.add('fa-eye-slash');
play=0;
return false;
// Stop the jquery function here
}
}
}

Related

Vanilla JS equivalent to jQuery $.once()?

Working on a Drupal 9 site and trying to add some custom JS code to a page.
Drupal.behaviors.syfyGlobalHideMenu = {
attach: function (context, settings) {
$('.nav-flyout', context).once('remove-modals', function () {
$(document).keyup(function (e) {
if (e.keyCode == 27) {
$('.nav-flyout', context).removeClass('js-flyout-active');
}
});
});
}
};
Wondering if there's a vanilla JS equivalent to the jQuery .once functionality above?
Currently Drupal attaches the event listener multiple times and I am trying to avoid that as I only want to attach the event listener once but have it remain attached and run every time the event is invoked.
let intervalID = null;
const search = document.querySelector(".call-us-table input#edit-search");
search.addEventListener("keydown", event => {
form.setAttribute("onsubmit", "return false");
clearInterval(intervalID);
});
search.addEventListener("keyup", event => {
intervalID = setInterval(submitForm, 2000);
});
Jquery once adds an html attribute to check if is the first time to run.
function vanillaOnce() {
if (!document.body.getAttribute('data-once')) {
document.body.setAttribute('data-once', 'true');
return true;
} else {
return false;
}
}
if (vanillaOnce) {
console.log('runs only once');
}

How to terminate map.on() function for Mapbox?

I used the Mapbox JS API for showing coordinates. This is the link of the document: https://docs.mapbox.com/mapbox-gl-js/example/mouse-position/
I have two buttons. After I click the first one, when the mouse is hovering the map, it shows the coordinates.
What I want to do is that after I click the second button, the previous running function can terminate. Can you help me on that?
function showCor() {
map.on('mousemove', function (e) {
document.getElementById('coord-info-lat').innerHTML =
JSON.stringify(e.lngLat.lat.toFixed(5));
document.getElementById('coord-info-lng').innerHTML =
JSON.stringify(e.lngLat.lng.toFixed(5));
});
}
function notShowCor() {
// Please help me here.
}
Immediately i can think of 2 options that might help you;
1.Change the html to equal ""
function notShowCor() {
map.on('mousemove', function (e) {
document.getElementById('coord-info-lat').innerHTML = "";
document.getElementById('coord-info-lng').innerHTML = "";
});
}
Set both elements to have opacity 0 (Though it would technically still be running)
Assuming you had CSS styles as follows:
#coord-info-lat, #coord-info-lng {
opacity:0;
}
#coord-info-lat.shown, coord-info-lng.shown {
opacity: 1;
}
function showCor() {
map.on('mousemove', function (e) {
var lat = document.getElementById('coord-info-lat');
var lng = document.getElementById('coord-info-lng');
lat.innerHTML = JSON.stringify(e.lngLat.lat.toFixed(5));
lng.innerHTML = JSON.stringify(e.lngLat.lng.toFixed(5));
lat.className = "shown";
lng.className = "shown";
});
}
function notShowCor() {
document.getElementById('coord-info-lat').className = "";
document.getElementById('coord-info-lng').className = "";
}
You could also do a combination of the 2
I solved the problem by setting an 'isActive' flag. Here is my code.
let isActive = true;
//function to show the position
function showCor() {
isActive = true;
map.on('mousemove', function (e) {
if (isActive) {
document.getElementById('coord-info-lat').innerHTML =
JSON.stringify(e.lngLat.lat.toFixed(5));
document.getElementById('coord-info-lng').innerHTML =
JSON.stringify(e.lngLat.lng.toFixed(5));
}
});
}
//function to clear the info and terminate the function.
function notShowCor() {
isActive = false;
document.getElementById('coord-info-lat').innerHTML = 'N/A';
document.getElementById('coord-info-lng').innerHTML = 'N/A';
}
Please advise if you have better solutions. Thank you.

custom when statement not firing functions

I am trying to make a when statement but it is not working as planned. Basically its a function to call another function when try. First before I explain further here is the syntax
when(function() {
//code here
});
Now basically... Think this way.. We have a progressbar.. We also have a custom event such as...
var pBarEvent = document.createEvent('Event');
pBarEvent.initEvent('pbardone', true, true);
document.addEventListener('pbardone', function() {
//code here
});
//if progress bar reaches 100 dispatchEvent
if (document.querySelector(".progress-bar").style.width === 100 + "%")
{
document.dispatchEvent(pBarEvent);
}
Now that piece of code is an example. If the document loads and its for instance at 50% it wont trigger until you add another event such as keydown or click. I dont want to do that I want to do.... "when" progress bar width equals 100% trigger it. Thats basically what needs to happen. So here is the code for the when statement so far (keep in mind its not the best looking one. As I dont normally do this but I wanted to keep this dynamic and who knows someone who later wants to do this can look at this question)
when function
function when(func)
{
var nowActive = false;
if (!typeof func === 'undefined')
{
func = new Function();
}
if (func)
{
nowActive = true;
clearInterval(whenStatementTimer);
}
else
{
nowActive = false;
var whenStatementTimer = setInterval(function() {
switch(func)
{
case true:
{
nowActive = true;
when();
break;
}
case false:
{
nowActive = false;
when();
break;
}
}
}, 1000);
}
if (nowActive === true)
{
func();
}
}
Now this does not work when I go to try something like....
when(function() {
SmartLeadJS.SmartLeadEvents.customEvents.progressBarFull(function() {
alert("100%");
SmartLeadJS.SmartLeadAds.LeadView.ChromeExtension.General.DynamicStyles.$.style("body", "background", "black");
});
});
It does not trigger. I need help possibly getting this when statement to work. What am I doing wrong? What can I do to fix it? No errors get thrown but it never fires.
edit based on answer
Function tried
function when(currentValue)
{
try
{
var o = {};
o.currentValue = currentValue;
o.do = function(func)
{
if (!typeof func === 'undefined')
{
func = new Function();
}
if (this.currentValue)
{
func();
}
else
{
setTimeout(this.do(func), 100);
}
};
return o;
}
catch(e)
{
console.log(e);
}
}
used as
when(true).do(function() {
SmartLeadJS.SmartLeadEvents.customEvents.progressBarFull(function() {
alert("This divs going through changes!!");
SmartLeadJS.SmartLeadAds.LeadView.ChromeExtension.General.DynamicStyles.$.style(".div", "background", "black");
});
});
This does not work. It never fires. But if I use a onclick listener as such it fires
document.addEventListener("click", function() {
SmartLeadJS.SmartLeadEvents.customEvents.progressBarFull(function() {
alert("This divs going through changes!!");
SmartLeadJS.SmartLeadAds.LeadView.ChromeExtension.General.DynamicStyles.$.style(".div", "background", "black");
});
}, false);
function when(statement){
o={};
o.statement=statement;
o.do=function(func){
awhen(this.statement,func);
};
return o;
}
function awhen(statement,func){
if(eval(statement)){
func();
}else{
window.setTimeout(function(){awhen(statement,func);},100);
}
}
Use:
when("true").do(function(){});
It works now :) . Its important to put the condition in ""!

Mini Refactoring Javascript Code

I want to optimize my Js code, at the moment i am rewriting the same function to launch a game in a popup. The only difference between the functions (open_web_client, open_web_client_2) is the openPopup size
I would like to use the same function for both games launched in the pop up, how can i use just a function for both in order to avoid repeating all the code?
This is the code
$(document).ready(function() {
web_client();
});
var web_client = function() {
var open_web_client = function(e) {
e.preventDefault();
if (!app.userIsLoggedIn()) {
app.showLoginPopup(translate.login_required_to_play_for_real);
} else {
if (Utils.analytics_enabled()) {
Utils.analytics_track_click('Play', $(this).attr("data-game-name"));
}
new GameWindow($(this).attr('href'), 'LOBBY').openPopup('1100x800');
}
}
var open_web_client_2 = function(e){
e.preventDefault();
if(!app.userIsLoggedIn()){
app.showLoginPopup(translate.login_required_to_play_for_real);
} else {
if(Utils.analytics_enabled()){
Utils.analytics_track_click('Play', $(this).attr("data-game-name"));
}
new GameWindow($(this).attr('href'), 'LOBBY').openPopup('1024x768');
}
}
if ($("a.ea_client").size() > 0) {
$('a.ea_client').on("click", open_web_client);
$('a.oneworks_client').on("click", open_web_client_2);
}
};
The only difference between the two functions is the value that is passed to openpopup.
So create a common function and pass the dimensions to the event handler.
var open_web_client = function(e) {
e.preventDefault();
if (!app.userIsLoggedIn()) {
app.showLoginPopup(translate.login_required_to_play_for_real);
} else {
if (Utils.analytics_enabled()) {
Utils.analytics_track_click('Play', $(this).attr("data-game-name"));
}
//here the hardcoded value is replaced with e.data.dim
new GameWindow($(this).attr('href'), 'LOBBY').openPopup(e.data.dim);
}
};
then modify the handler code to pass the dimensions uniquely
$('a.ea_client').on("click",{dim:'1100x800'}, open_web_client);
$('a.oneworks_client').on("click",{dim:'1024x768'}, open_web_client);
arguments passed this way to handlers can be accessed through data property present in the event object.
The only difference between the functions (open_web_client, open_web_client_2) is the openPopup size
That is basically begging to become a parameter of your function:
function open_web_client(e, size) {
e.preventDefault();
if (!app.userIsLoggedIn()) {
app.showLoginPopup(translate.login_required_to_play_for_real);
} else {
if (Utils.analytics_enabled()) {
Utils.analytics_track_click('Play', $(this).attr("data-game-name"));
}
new GameWindow($(this).attr('href'), 'LOBBY').openPopup(size);
}
}
$('a.ea_client').on("click", function(e) {
open_web_client(e, '1100x800');
});
$('a.oneworks_client').on("click", function(e) {
open_web_client(e, '1024x768');
});
A littlebit more advanced technique is to use a closure, with a function that creates the listener:
function make_web_client_opener(size) {
return function open_web_client(e) {
e.preventDefault();
if (!app.userIsLoggedIn()) {
app.showLoginPopup(translate.login_required_to_play_for_real);
} else {
if (Utils.analytics_enabled()) {
Utils.analytics_track_click('Play', $(this).attr("data-game-name"));
}
new GameWindow($(this).attr('href'), 'LOBBY').openPopup(size);
}
};
}
$('a.ea_client').on("click", make_web_client_opener('1100x800'));
$('a.oneworks_client').on("click", make_web_client_opener('1024x768'));

timer doesn't stop on buttonclick

I have trouble with timer in button click. When i click button startpause() method is called there i set start timer and stop timer. It works fine when I click button normally(one click after sometime another click) but when I click the button again and again speedly the timer starts to jump with 2-3 secs. Seems like more than one timer is running.. Anyone have any idea....?? here time is my timer method
function startpause() {
if(FLAG_CLICK) {
setTimeout(tim,1000);
FLAG_CLICK = false;
}
else {
clearTimeout(ti);
FLAG_CLICK = true;
}
}
function tim() {
time.innerHTML = t;
t = t + 1;
ti= setTimeout("tim()", 1000);
}
Try this:
// assuming you declared ti and t out here, cuz I hope they're not global
var t = 0;
var ti;
var running = false;
function startpause() {
clearTimeout(ti);
if(!running) {
ti = setTimeout(tim,1000);
running = true;
} else {
running = false;
}
}
function tim() {
time.innerHTML = t;
t = t + 1;
ti = setTimeout(tim,1000);
}
You can read more about the .setTimeout() here: https://developer.mozilla.org/en/docs/DOM/window.setTimeout
Also, see the jsfiddle I just created: http://jsfiddle.net/4BMhd/
You need to store setTimeout somewhere in order to manipulate it later.
var myVar;
function myFunction()
{
myVar=setTimeout(function(){alert("Hello")},3000);
}
function myStopFunction()
{
clearTimeout(myVar);
}
ref http://www.w3schools.com/js/js_timing.asp
Maybe you must change this:
if(FLAG_CLICK) {
setTimeout(tim,1000);
FLAG_CLICK = false;
}
to:
if(FLAG_CLICK) {
tim();
FLAG_CLICK = false;
}
It seems works for me normally

Categories