JQuery Refactoring ( separate codes by functionality, improve readability) - javascript

recently I have been studying way of refactoring Jquery code to handling UI events.
It was hard to find documents which wrote recently.
So, I write my result via this document and hope reviewing my decision from skilled developers such as you.
<purpose of refactoring>
separate codes by functionality
improve readability
Jquery source is composed by html elements' event. So I usually saw coding style below
$("#nameText").on("input", function () {
//Some of actions to control html elements, extract data, validation, ajax request, etc,,,
}
$("#surveyText").on("input", function () {
//Some of actions to control html elements, extract data, validation, ajax request, etc,,,
}
$("#submitBtn").on("click", function (e) {
//Some of actions to control html elements, extract data, validation, ajax request, etc,,,
}
It's pretty simple and we can read which action is needed and conducted by some elements action.
But that could be verbose and confusing us because there are many roles and we have to check the element's css attributes which related selector.
Some times, css class name or id don't have proper name which not enough explain role of element or in case of, use navigator function like find() or selector by element hierarchy.
$("#s_f01").find("li").on("click", function () {
//Some of actions to control html elements, extract data, validation, ajax request, etc,,,
}
$(".s_btn01").on("click", function () {
//Some of actions to control html elements, extract data, validation, ajax request, etc,,,
}
$("#submitBtn").on("click", function (e) {
//Some of actions to control html elements, extract data, validation, ajax request, etc,,,
}
And functions for particular element could be spread out by modified history for adding function or some of modification.
//Codes for Survey Form (line 10 - 200)
$("#s_f01").find("li").on("click", function () {
//Some of actions to control html elements, extract data, validation, ajax request, etc,,,
}
$(".s_btn01").on("click", function () {
//Some of actions to control html elements, extract data, validation, ajax request, etc,,,
}
$("#submitBtn").on("click", function (e) {
//Some of actions to control html elements, extract data, validation, ajax request, etc,,,
}
,,,
//added after statistics function for enable Survey form action(line 1200)
$("#SurveyFormOpenBtn").on("click", sendStatisticInfo_SurveyFormOpened());

<Solution>
separate functions by Component to make sure functions will be used by which Component
each object have Event and Function. Event will have argument which will be passed by Jquery Element and functions will be used by Events.
it makes more easily understanding each function's purpose
it prevent spread out particular Element's functions.
$(function () {
var categoryListArea = {
someEvent: function ($jqueryEl) { },
someFunc: function (str, etc) {}
}
var survayArea = {
someEvent: function ($jqueryEl) { },
someFunc: function (str, etc) {}
}
var HeaderArea = { }
extract code by functionality and declare as function and event to number 1's xxxArea Object.
via Event function name, we can understand what will be conducted by triggered jquery function.
each xxxArea Object make more easily separate functions by each components.
each functions will be maintained by each components.
//AS-IS
$("#nameText").on("input", function () {
console.log('test');
var inputtedText = $(this).val();
//1. Dicide display status of Name Lable Element
if (inputtedText !== '') {
$('#surveyLable').show();
} else {
$('#surveyLable').hide();
}
//2. Dicide display status of Name input Element
if (inputtedText !== '') {
$('#surveyText').show();
} else {
$('#surveyText').hide();
}
//3. Prevent input html characotrs
if (validateHtml(inputtedText)) {
alert('&<>\"\'\`=/ are not allowed');
$(this).val(escapeHtml(inputtedText));
}
});
//TO-Be
var survayArea = {
inputNameTextEvent: function ($el) {
var inputtedText = $el.val();
//1. Dicide display status of Name Lable Element
survayArea.swithDisplayStatus(inputtedText, $('#surveyLable'));
//2. Dicide display status of Name input Element
survayArea.swithDisplayStatus(inputtedText, $('#surveyText'));
//3. Prevent input html characotrs
// validateHtml and escapeHtml is used commonly so don't include particular object which represents some component
if (validateHtml(inputtedText)) {
alert('&<>\"\'\`=/ are not allowed');
$el.val(escapeHtml(inputtedText));
}
},
swithDisplayStatus: function (str, El) {
//Decide display status
if (str !== '') {
El.show();
} else {
El.hide();
}
}
}
$("#nameText").on("input", function () {
survayArea.inputNameTextEvent($(this));
});
function validateHtml(string) {
let reg = /[&<>"'`=\/]/g
return reg.test(string);
}
function escapeHtml(string) {
return String(string).replace(/[&<>"'`=\/]/g, '');
};
hire is my sample code which explain concept.
if there are more efficient or more practical way, please let me know.
<SAMPLE CODE>
sample.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<script
src="https://code.jquery.com/jquery-3.6.0.min.js"
integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4="
crossorigin="anonymous"
></script>
<script src="sample.js"></script>
<style>
ul#category-tabs {
list-style: none;
padding: 0;
margin: 0;
padding: 0;
}
ul#category-tabs li {
display: block;
position: relative;
margin: 0;
border-bottom: 1px #ececec solid;
padding: 10px 18px;
}
ul.sub-category-tabs li {
padding: 2px !important;
}
ul.sub-category-tabs li {
border-bottom: 0px !important;
}
ul#category-tabs li a {
color: #333;
font-weight: 700;
margin-bottom: 0;
font-size: 12px;
}
ul#category-tabs li a i {
top: 12px;
right: 18px;
position: absolute;
cursor: pointer;
width: 16px;
height: 16px;
padding: 2px;
color: #ed6663;
}
.bodyContainer {
float: left;
overflow: auto;
position: relative;
}
</style>
</head>
<body>
<div id="headerArea" class="bodyContainer">
<div class="barCategory" id="barCategory">
<ul id="category-tabs">
<li>
<a href="javascript:void" class="main-category">
Home<i class="fa fa-minus"></i
></a>
<ul class="sub-category-tabs">
<li>CompanyInfo</li>
<li>Product</li>
<li>Pricing</li>
<li>Contact</li>
</ul>
</li>
</ul>
</div>
</div>
<div id="survayArea" class="bodyContainer">
<h3>Dummy survey form</h3>
<div>
<form action="" id="surveyForm">
<div id="nameLable">Name:</div>
<input
type="text"
id="nameText"
value=""
placeholder="Please input name"
/><br /><br />
<div id="surveyLable" style="display: none">Survey:</div>
<input
type="text"
id="surveyText"
style="display: none"
/><br /><br />
<input
type="button"
id="submitBtn"
value="Submit"
style="display: none"
/>
</form>
</div>
</div>
</body>
</html>
AS-IS
sample.js
$(function () {
$("#nameText").on("input", function () {
console.log('test');
var inputtedText = $(this).val();
//1. Dicide display status of Name Lable Element
if (inputtedText !== '') {
$('#surveyLable').show();
} else {
$('#surveyLable').hide();
}
//2. Dicide display status of Name input Element
if (inputtedText !== '') {
$('#surveyText').show();
} else {
$('#surveyText').hide();
}
//3. Prevent input html characotrs
if (validateHtml(inputtedText)) {
alert('&<>\"\'\`=/ are not allowed');
$(this).val(escapeHtml(inputtedText));
}
});
$("#surveyText").on("input", function () {
var inputtedText = $(this).val();
//1. Dicide display status of Submit Button
if (inputtedText !== '') {
$('#submitBtn').show();
} else {
$('#submitBtn').hide();
}
//2. Prevent input html characotrs
if (validateHtml(inputtedText)) {
alert('&<>\"\'\`=/ are not allowed');
$(this).val(escapeHtml(inputtedText));
}
});
$("#submitBtn").on("click", function (e) {
e.preventDefault();
//1. Submit survey form
$("#surveyForm").trigger("submit");
});
})
function validateHtml(string) {
let reg = /[&<>"'`=\/]/g
return reg.test(string);
}
function escapeHtml(string) {
return String(string).replace(/[&<>"'`=\/]/g, '');
};
TO-BE
sample.js
$(function () {
var headrAreaEvents = {
//...
}
var survayArea = {
inputNameTextEvent: function ($el) {
var inputtedText = $el.val();
//1. Dicide display status of Name Lable Element
survayArea.swithDisplayStatus(inputtedText, $('#surveyLable'));
//2. Dicide display status of Name input Element
survayArea.swithDisplayStatus(inputtedText, $('#surveyText'));
//3. Prevent input html characotrs
survayArea.preventHtmlCharactors(inputtedText, $(this));
},
swithDisplayStatus: function (str, $el) {
//Dicide display status
if (str !== '') {
$el.show();
} else {
$el.hide();
}
},
inputSurveyTextEvent: function ($el) {
var inputtedText = $el.val();
//1. Dicide display status of Submit Button
survayArea.swithDisplayStatus(inputtedText, $('#submitBtn'));
//2. Prevent input html characotrs
survayArea.preventHtmlCharactors(inputtedText, $(this));
},
preventHtmlCharactors: function (inputtedText) {
if (validateHtml(inputtedText, $el)) {
alert('&<>\"\'\`=/ are not allowed');
$el.val(escapeHtml(inputtedText));
}
},
submitSurveyFormEvent: function ($el) {
$("#surveyForm").trigger("submit");
}
}
$("#nameText").on("input", function () {
survayArea.inputNameTextEvent($(this));
});
$("#surveyText").on("input", function () {
survayArea.inputSurveyTextEvent($(this));
});
$("#submitBtn").on("click", function () {
survayArea.submitSurveyFormEvent($(this));
});
})
function validateHtml(string) {
let reg = /[&<>"'`=\/]/g
return reg.test(string);
}
function escapeHtml(string) {
return String(string).replace(/[&<>"'`=\/]/g, '');
};
complement
// actually, there aren't need to pass param $(this) to submitSurveyFormEvent method.
submitSurveyFormEvent: function ($el) {
$("#surveyForm").trigger("submit");
}
$("#submitBtn").on("click", function () {
survayArea.submitSurveyFormEvent($(this));
});
//So I tried to remove on event's anonymous function and input survayArea.submitSurveyFormEvent() directly.
//But if do that, submit event was executed infinitely (like executed infinite loop)
//if anyone knows why about this, pleas let me know.
$("#submitBtn").on("click",survayArea.submitSurveyFormEvent());

Related

How can I avoid passing a parameter to each function but still have access to it inside the function

When I click the button, I am opening a Jquery dialog and creating an object of CustomClass. I need this object in different functions. Is there a way to avoid passing it to each function but still have access to it inside the function?
Note: I am using the same code to open multiple dialogs through different click events.
JS Fiddle Link: https://jsfiddle.net/gwphxssq/1/
HTML:
<div class='btn1'>Button1</div>
<div class='btn2'>Button2</div>
<p class='plain-text'> Two dialog's open, one behind the other. Please drag the top dialog to see the other dialog below.
</p>
JS:
var Test = Test || {};
Test = {
CustomClass: function(fnSave) {
return {
dialogElem: null,
saveBtn: null,
fnSave: fnSave
}
},
Cache: function(obj, dialogElem) {
obj.dialogElem = $(dialogElem);
obj.saveBtn = $(dialogElem).find('.btnSave');
},
OpenDialog: function(option) {
var that = this;
var dynamicElem = '<div>Dialog' +
'<input type="button" class="btnSave" value="Save"/>' + '</div>';
var obj = new that.CustomClass(option);
$(dynamicElem).dialog({
open: function(event, ui) {
that.Cache(obj, this);
}
});
//obj is being passed to different functions. How can I avoid passing it to each function but still have access to the obj in each of the functions below?
that.BindEvents(obj);
that.SampleFunc1(obj);
that.SampleFunc2(obj);
},
BindEvents: function(obj) {
obj.saveBtn.on('click', function() {
obj.fnSave();
});
},
SampleFunc1: function(obj) {
//Need the obj here too
//Some code
},
SampleFunc2: function(obj) {
//Need the obj here too
//Some code
}
}
//Click Event for Button 1
$('.btn1').on('click', function() {
Test.OpenDialog(function() {
alert('First Dialog');
});
});
//Click Event for Button 2
$('.btn2').on('click', function() {
Test.OpenDialog(function() {
alert('Second Dialog');
});
});
CSS:
.btn1,
.btn2 {
background-color: grey;
width: 200px;
height: 20px;
text-align: center;
padding: 3px;
margin-bottom: 5px;
display: inline-block;
}
.plain-text {
color: red;
}
.btnSave {
float: right;
width: 80px;
height: 30px;
}
You could do a factory which creates new functions, and those functions have the object in their closure. For example:
OpenDialog: function (option) {
var that = this;
var dynamicElem = '<div>Dialog' +
'<input type="button" class="btnSave" value="Save"/>' + '</div>';
var obj = new that.CustomClass(option);
var fxns = that.createFxns(obj);
fxns.bindEvents();
fxns.sampleFunc1();
fxns.sampleFunc2();
},
createFxns: function(obj) {
return {
bindEvents: function () {
obj.on('click', function () {
obj.fnSave();
}
},
sampleFunc1: function () {},
sampleFunc2: function () {}
}
}
I don't see that you get much out of this pattern though. The main benefit of this is that you could pass those functions around to some other piece of code, and have the object already 'baked in'. That way the other piece of code doesn't even need to know that obj exists. In your case though, you're just calling them right away, and your class clearly needs to know about the existence of obj.

How can I interact with browser control+z/control+y for undo/redo?

I'm creating my own editor, and I'm finally tackling the undo/redo issue that I've been dodging for weeks.
I have created the base framework for storing and traversing the history of custom actions, but I cannot seem to find good information on how to interact with the browsers history in a contentEditable area.
Looking at https://github.com/jzaefferer/undo/blob/master/undo.js, I still do not see how this is done.
I can undo/redo my custom actions, but I'm oblivious to how I can tap into the browsers default history.
Will I have to add all of the original functionality if I am to override the default control + ( z | y )?
Update: Where can I find more information about how the browser handles these undo/redo actions?
Check out the source of the contenteditable demo to figure out more about how he attached the library to the div.
$(function() {
var stack = new Undo.Stack(),
EditCommand = Undo.Command.extend({
constructor: function(textarea, oldValue, newValue) {
this.textarea = textarea;
this.oldValue = oldValue;
this.newValue = newValue;
},
execute: function() {
},
undo: function() {
this.textarea.html(this.oldValue);
},
redo: function() {
this.textarea.html(this.newValue);
}
});
stack.changed = function() {
stackUI();
};
var undo = $(".undo"),
redo = $(".redo"),
dirty = $(".dirty");
function stackUI() {
undo.attr("disabled", !stack.canUndo());
redo.attr("disabled", !stack.canRedo());
dirty.toggle(stack.dirty());
}
stackUI();
$(document.body).delegate(".undo, .redo, .save", "click", function() {
var what = $(this).attr("class");
stack[what]();
return false;
});
var text = $("#text"),
startValue = text.html(),
timer;
$("#text").bind("keyup", function() {
// a way too simple algorithm in place of single-character undo
clearTimeout(timer);
timer = setTimeout(function() {
var newValue = text.html();
// ignore meta key presses
if (newValue != startValue) {
// this could try and make a diff instead of storing snapshots
stack.execute(new EditCommand(text, startValue, newValue));
startValue = newValue;
}
}, 250);
});
$(".bold").click(function() {
document.execCommand("bold", false);
var newValue = text.html();
stack.execute(new EditCommand(text, startValue, newValue));
startValue = newValue;
});
// This is where he attaches the observer for undo / redo.
// For more information: https://stackoverflow.com/questions/16006583/capturing-ctrlz-key-combination-in-javascript
$(document).keydown(function(event) {
if (!event.metaKey || event.keyCode != 90) {
return;
}
event.preventDefault();
if (event.shiftKey) {
stack.canRedo() && stack.redo()
} else {
stack.canUndo() && stack.undo();
}
});
});
Capturing ctrl+z key combination in javascript
Use this, but it works as it should only with <div contentEditable="true"> boxes. In textarea it undoes and redoes all text at once, not word by word as in div.
<script language="JavaScript">
function Undo() { document.execCommand("undo", false, null); }
function Redo() { document.execCommand("redo", false, null); }
</script>
<div contentEditable="true" style="background-color:rgba(0,0,0,0.8); resize:none; width: 499px; height: 230px; border: 1px solid red;"></div>
<input type="button" onmouseup="Undo()" value="Undo" />
<input type="button" onmouseup="Redo()" value="Redo" />
I don't believe there is anyway to directly access the contents of the undo buffer, but you can trigger an undo or redo using document.execCommand. Simple example:
<html>
<head>
<style>
#box {
width: 200px;
height: 100px;
background-color: grey;
}
</style>
</head>
<body>
<div id="box" contenteditable="true"></div>
<button id="undo">Undo</button>
<button id="redo">Redo</button>
<script>
var box = document.getElementById('box');
var undo = document.getElementById('undo');
var redo = document.getElementById('redo');
undo.addEventListener('click', function (ev) {
document.execCommand('undo', false, null);
});
redo.addEventListener('click', function (ev) {
document.execCommand('redo', false, null);
});
</script>
</body>
</html>
Check it is out as a jsfiddle.

setInterval + image src changes when clicked on button

I want to give blink effect(dark and light) when clicked on the button.I have written the following code but it does not work.So please help me.
$(document).ready(function () {
$(".search").click(function () {
setInterval(function () {
var curSrc = $("#red").attr('src');
if (curSrc === '../images/lightred.jpg') {
$(curSrc).attr("src", "../images/Darkred.jpg");
}
if (curSrc === '../images/Darkred.jpg') {
$(curSrc).attr("src", "../images/lightred.jpg");
}
}, 2000);
});
});
curSrc is your source attribute, yet you are trying to wrap it in jQuery, that won't make it an object. You'll have to target #red again and then set the source:
if (curSrc === '../images/lightred.jpg') {
$("#red").attr("src", "../images/Darkred.jpg");
}
if (curSrc === '../images/Darkred.jpg') {
$("#red").attr("src", "../images/lightred.jpg");
}
It seems the question might be how to make the button blink. This can be done with the css background-color property. CSS is a better fit, assuming lightRed and darkRed are solid colors. If the images are required you can use the background-image property.
<input type="button" class="search lightRed" value="Search"/>
<style>
.lightRed { background-color: lightcoral }
.darkRed { background-color: darkRed }
</style>
<script>
$(document).ready(function(){
$(".search").click(function(){
setInterval(function(){
var isLightRed = $(".search").hasClass("lightRed");
if (isLightRed) {
$(".search").removeClass("lightRed").addClass("darkRed");
} else {
$(".search").removeClass("darkRed").addClass("lightRed");
}
},2000);
});
});
</script>

Why is my JavaScript for suspending and unsuspending a user not working correctly?

I'm building a site for someone and on the Admin side there is a "Manage Users" page to manage the website's users. Here is my two functions to suspend and unsuspend (and for the alert):
var admin = {
alert: (function(msg,dur) {
if(!dur || dur == null) {
dur = 1500;
}
$('#alert_box2').remove();
$('body').append('<div id="alert_box2" style="width: 100%; height: 9px; top: -17px; left: 0; position: absolute; text-align: center; z-index: 5;"><div id="alert_box_inner2"></div></div>');
$('#alert_box2').show(0, function() {
if(dur!=='none') {
$('#alert_box_inner2').html(msg).stop(true, true).fadeIn(800).delay(dur).fadeOut(800, function() {
$('#alert_box2').remove();
});
}
else {
$('#alert_box_inner').html(msg).show();
}
});
}),
suspendUser: (function(id) {
admin.alert('Please wait...',20000);
$.get('user_more_actions.php?action=suspend&nolightbox=1&id='+id, function(data,textStatus) {
setTimeout(function() {
if(textStatus=='success') {
if(data.indexOf('suspended') > -1) {
name = data.replace('suspended ','');
admin.alert(name+' is now suspended.',2500);
$('#status_'+id).html('<strong style="color: red;">Suspended</strong>');
$('#suspend_'+id).attr('id','unsuspend_'+id).text('Unsuspend').removeClass('suspend').addClass('unsuspend');
}
else {
admin.alert('Sorry, there was an error. <span class="s_link" onclick="$(\'#suspend_'+id+'\').click();">Try again</a>','none');
}
}
else {
admin.alert('Sorry, there was an error. <span class="s_link" onclick="$(\'#suspend_'+id+'\').click();">Try again</a>','none');
}
}, 500);
});
}),
unsuspendUser: (function(id) {
admin.alert('Please wait...',20000);
$.get('user_more_actions.php?action=unsuspend&nolightbox=1&id='+id, function(data,textStatus) {
setTimeout(function() {
if(textStatus=='success') {
if(data.indexOf('unsuspended') > -1) {
name = data.replace('unsuspended ','');
admin.alert(name+' is no longer suspended.',2500);
$('#status_'+id).html('<strong style="color: green;">Active</strong>');
$('#unsuspend_'+id).attr('id','suspend_'+id).text('Suspend').removeClass('unsuspend').addClass('suspend');
}
else {
admin.alert('Sorry, there was an error. <span class="s_link" onclick="$(\'#unsuspend_'+id+'\').click();">Try again</a>',20000);
}
}
else {
admin.alert('Sorry, there was an error. <span class="s_link" onclick="$(\'#unsuspend_'+id+'\').click();">Try again</a>',20000);
}
}, 500);
});
})
};
And the code that triggers the functions when a Suspend or Unsuspend link is clicked:
$('.suspend').each(function() {
$(this).live('click', function(e) {
e.preventDefault();
var id = $(this).attr('id').replace('suspend_', '');
admin.suspendUser(id);
});
});
$('.unsuspend').each(function() {
$(this).live('click', function(e) {
e.preventDefault();
var id = $(this).attr('id').replace('unsuspend_', '');
admin.unsuspendUser(id);
});
});
Everything is working ok, except when I click again it messes up. When a Suspend link is clicked, it changes to Unsuspend (and changes the ID). But then if I click Unsuspend it doesn't work, and it is calling the admin.suspend() function instead of admin.unsuspend() (and the ID isn't being passed so the name isn't displayed):
When the class and the ID is changed it should call either the admin.suspend(id_here) or admin.unsuspend(id_here); but it isn't.
Does anyone know why this is happening? Thanks in advance and I'm sorry that this post is long.
I've fiddled with it. Hope this helps:http://jsfiddle.net/wKGKu/
Update: After reading your concerns for .each, I've updated the code to demonstrate it isn't needed: http://jsfiddle.net/wKGKu/2/
I believe the way you wrote your live bindings is incorrect, they should have been bound like this:
$('.suspend').live('click', function(e) {
e.preventDefault();
var id = $(this).attr('id').replace('suspend_', '');
admin.suspendUser(id);
});
$('.unsuspend').live('click', function(e) {
e.preventDefault();
var id = $(this).attr('id').replace('unsuspend_', '');
admin.unsuspendUser(id);
});
I simplified fiddle showing the working code at: jsFiddle
You are attaching events to suspend/unsuspend classes, but your AJAX callback is modifying id attribute. Also you are horribly misusing live(). In the end your handler is already attached to the link and doesn't change after your AJAX calls.
Solution is to
1) leave ID's alone - you are only confusing yourself by modifying them
2) rewrite event handler to either not do each() or not use live - put together completely defeats purpose behind live()
$('.suspend').live('click', function(){
var id = $(this).attr('id').replace('suspend_', '');
admin.suspendUser(id);
return false;
});
$('.unsuspend').live('click', function(e){
var id = $(this).attr('id').replace('suspend_', '');
admin.unsuspendUser(id);
return false;
});

How do I clear this setInterval inside a function?

Normally, I’d set the interval to a variable and then clear it like var the_int = setInterval(); clearInterval(the_int); but for my code to work I put it in an anonymous function:
function intervalTrigger() {
setInterval(function() {
if (timedCount >= markers.length) {
timedCount = 0;
}
google.maps.event.trigger(markers[timedCount], "click");
timedCount++;
}, 5000);
};
intervalTrigger();
How do I clear this? I gave it a shot and tried var test = intervalTrigger(); clearInterval(test); to be sure, but that didn’t work.
Basically, I need this to stop triggering once my Google Map is clicked, e.g.
google.maps.event.addListener(map, "click", function() {
//stop timer
});
The setInterval method returns a handle that you can use to clear the interval. If you want the function to return it, you just return the result of the method call:
function intervalTrigger() {
return window.setInterval( function() {
if (timedCount >= markers.length) {
timedCount = 0;
}
google.maps.event.trigger(markers[timedCount], "click");
timedCount++;
}, 5000 );
};
var id = intervalTrigger();
Then to clear the interval:
window.clearInterval(id);
// Initiate set interval and assign it to intervalListener
var intervalListener = self.setInterval(function () {someProcess()}, 1000);
function someProcess() {
console.log('someProcess() has been called');
// If some condition is true clear the interval
if (stopIntervalIsTrue) {
window.clearInterval(intervalListener);
}
}
the_int=window.clearInterval(the_int);
Simplest way I could think of: add a class.
Simply add a class (on any element) and check inside the interval if it's there. This is more reliable, customisable and cross-language than any other way, I believe.
var i = 0;
this.setInterval(function() {
if(!$('#counter').hasClass('pauseInterval')) { //only run if it hasn't got this class 'pauseInterval'
console.log('Counting...');
$('#counter').html(i++); //just for explaining and showing
} else {
console.log('Stopped counting');
}
}, 500);
/* In this example, I'm adding a class on mouseover and remove it again on mouseleave. You can of course do pretty much whatever you like */
$('#counter').hover(function() { //mouse enter
$(this).addClass('pauseInterval');
},function() { //mouse leave
$(this).removeClass('pauseInterval');
}
);
/* Other example */
$('#pauseInterval').click(function() {
$('#counter').toggleClass('pauseInterval');
});
body {
background-color: #eee;
font-family: Calibri, Arial, sans-serif;
}
#counter {
width: 50%;
background: #ddd;
border: 2px solid #009afd;
border-radius: 5px;
padding: 5px;
text-align: center;
transition: .3s;
margin: 0 auto;
}
#counter.pauseInterval {
border-color: red;
}
<!-- you'll need jQuery for this. If you really want a vanilla version, ask -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="counter"> </p>
<button id="pauseInterval">Pause/unpause</button></p>

Categories