I am trying to modify Jira Tempo plugin's plan work form. So in the tempo time sheet page
I have a button who has 2 actions bind-ed, one is a click action and one is a focus out.
the click action opens a popup. and the focus out verifies the form in the popup. I need the clik action to be executed first and then the focus out.
The problem is when the popup opens there is a call to all of the three functions.
event.stopPropagation().preventDefault().stopImmediatePropagation(); so the focus out does not fire in chrome.
In IE10 and Firefox works great.
Can i override jQuery basic function ofevent.stopPropagation().preventDefault().stopImmediatePropagation() to do not apply for that button?
all three, maybe?
I tried this:
(function () {
jQuery.Event.prototype = {
isDefaultPrevented: returnFalse,
isPropagationStopped: returnFalse,
isImmediatePropagationStopped: returnFalse,
stopPropagation: function () {
if (jQuery('#tempo-plan-button').hasClass(this.currentTarget.className)) {
} else {
var e = this.originalEvent;
this.isPropagationStopped = returnTrue;
if (e && e.stopPropagation) {
e.stopPropagation();
}
}
},
preventDefault: function () {
if (jQuery('#tempo-plan-button').hasClass(this.currentTarget.className)) {
} else {
var e = this.originalEvent;
this.isDefaultPrevented = returnTrue;
if (e && e.preventDefault) {
e.preventDefault();
}
}
},
stopImmediatePropagation: function () {
if (jQuery('#tempo-plan-button').hasClass(this.currentTarget.className)) {
} else {
var e = this.originalEvent;
this.isImmediatePropagationStopped = returnTrue;
if (e && e.stopImmediatePropagation) {
e.stopImmediatePropagation();
}
this.stopPropagation();
}
}
};
function returnFalse() {
return false;
}
function returnTrue() {
return true;
}
})();
UPDATE:
I don't have control on what the click function does, but i have control on the focus out, I have made some test and i looks like Chrome does not see the focus out event, because the element is hidden before the focus out occurs ( it is a popup button).
I managed to call my functions with mouse out event but this does not work on IE so I have to bind separate event listener for IE and Chrome,Firefox,Safari.
Can you help with some browser detection examples.
UPDATE 2:
My problem solved with a different listener to the popup element. ex:
jQuery(document).ready(function ($) {
var currentUser = null;
var selected = null;
var opened = null;
var formOpened = null;
var activityField = null;
var activitySelected = null;
var popupBody = null;
var formOpened = null;
var periodCheckbox = null;
var dateField = null;
var endDateField = null;
var plannedHours = null;
var periodselected = null;
var days = 1;
var startdate = 0;
var enddate = 0;
var planButton = $('#tempo-plan-button');
//this is the default LM-Holiday activity ID set this
value to corespond with the value on jira tempo form.
var holidayid = "10100";
var holidaysLeft = 21; /*
$('#tempo-plan-button').click(function () {
alert("click event");
});
$('#tempo-plan-button').focusin(function () {
alert("focus event");
});
$('#tempo-plan-button').hover(function () {
alert("hover event");
});
$('#tempo-plan-button').mouseleave(function () {
alert("mouse leave event");
});
$('#tempo-plan-button').mouseout(function () {
alert("mouse out event");
}); */
$('body').one('focus', 'div[class="aui-popup aui-dialog"]', function (event) {
$('div[class="aui-popup aui-dialog"]').each(function () {
popupBody = $(this).find(".dialog-components");
if ($(this).find(".dialog-title").hasClass("tempo-add-button") === false) {
i = 0;
j = 0;
$(popupBody).find(".dialog-page-menu li").each(function () {
if ($(this).attr("class") === "page-menu-item selected") {
button = $(this).find('.item-button');
if ((button).text() === "Internal") {
selected = i;
}
}
i++;
});
$(popupBody).find(".dialog-panel-body").each(function () {
if ($(this).is(":visible")) {
opened = j;
formOpened = $(this).find('form');
}
j++;
});
if (selected === null) {
i = 0;
j = 0;
$(popupBody).find(".dialog-page-menu li").click(function () {
$(popupBody).find(".dialog-page-menu li").each(function () {
if ($(this).attr("class") === "page-menu-item selected") {
button = $(this).find('.item-button');
if ((button).text() === "Internal") {
selected = i;
}
}
i++;
});
$(popupBody).find(".dialog-panel-body").each(function () {
if ($(this).is(":visible")) {
opened = j;
formOpened = $(this).find('form');
}
j++;
});
if (selected === opened) {
activityField = $(formOpened).find('.tempo-activity-picker.select');
periodCheckbox = $(formOpened).find('.showperiod.tempo-show-period');
dateField = $(formOpened).find(' input[name="date"]');
endDateField = $(formOpened).find('input[name="enddate"]');
plannedHours = $(formOpened).find('input[name="time"]');
days = 1;
$(activityField).change(function () {
activitySelected = $(this).val();
});
$(periodCheckbox).change(function () {
if ($(this).prop("checked")) {
periodselected = true;
}
else
{
periodselected = false;
}
});
$(dateField).change(function () {
if (periodselected) {
startdate = parseDate($(this).val());
enddate = parseDate($(endDateField).val());
} else {
days = 1;
}
;
});
$(endDateField).change(function () {
startdatestring = $(dateField).val();
enddatestring = $(this).val();
startdate = parseDate(startdatestring);
enddate = parseDate(enddatestring);
});
$(plannedHours).off("focusin");
$(plannedHours).focusin(function () {
if (activitySelected === holidayid) {
if (periodselected) {
days = calcBusinessDays(startdate, enddate);
if (holidaysLeft >= days) {
holidaysLeft = holidaysLeft - days;
alert("Mai ai " + holidaysLeft + " zile de concediu ramase!");
$(popupBody).find('button[accesskey="s"]').removeAttr('disabled');
}
else {
$(popupBody).find('button[accesskey="s"]').attr('disabled', 'disabled');
alert('trebuie sa selectezi o perioada mai mica de' + holidaysLeft + 'de zile');
}
} else
{
if (holidaysLeft >= days) {
holidaysLeft = holidaysLeft - days;
alert("Mai ai " + holidaysLeft + " zile de concediu ramase!");
$(popupBody).find('button[accesskey="s"]').removeAttr('disabled');
}
else {
$(popupBody).find('button[accesskey="s"]').attr('disabled', 'disabled');
alert('trebuie sa selectezi o perioada mai mica de' + holidaysLeft + 'de zile');
}
}
}
});
}
});
} else {
j = 0;
$(popupBody).find(".dialog-panel-body").each(function () {
if ($(this).is(":visible")) {
opened = j;
formOpened = $(this).find('form');
}
j++;
});
if (selected === opened) {
activityField = $(formOpened).find('.tempo-activity-picker.select');
periodCheckbox = $(formOpened).find('.showperiod.tempo-show-period');
dateField = $(formOpened).find(' input[name="date"]');
endDateField = $(formOpened).find('input[name="enddate"]');
plannedHours = $(formOpened).find('input[name="time"]');
days = 1;
$(activityField).change(function () {
activitySelected = $(this).val();
});
$(periodCheckbox).change(function () {
if ($(this).prop("checked")) {
periodselected = true;
}
else
{
periodselected = false;
}
});
$(dateField).change(function () {
if (periodselected) {
startdate = parseDate($(this).val());
enddate = parseDate($(endDateField).val());
} else {
days = 1;
}
;
});
$(endDateField).change(function () {
startdatestring = $(dateField).val();
enddatestring = $(this).val();
startdate = parseDate(startdatestring);
enddate = parseDate(enddatestring);
});
$(plannedHours).off("focusin");
$(plannedHours).focusin(function () {
if (activitySelected === holidayid) {
if (periodselected) {
days = calcBusinessDays(startdate, enddate);
if (holidaysLeft >= days) {
holidaysLeft = holidaysLeft - days;
alert("Mai ai " + holidaysLeft + " zile de concediu ramase!");
$(popupBody).find('button[accesskey="s"]').removeAttr('disabled');
}
else {
$(popupBody).find('button[accesskey="s"]').attr('disabled', 'disabled');
alert('trebuie sa selectezi o perioada mai mica de' + holidaysLeft + 'de zile');
}
} else
{
if (holidaysLeft >= days) {
holidaysLeft = holidaysLeft - days;
alert("Mai ai " + holidaysLeft + " zile de concediu ramase!");
$(popupBody).find('button[accesskey="s"]').removeAttr('disabled');
}
else {
$(popupBody).find('button[accesskey="s"]').attr('disabled', 'disabled');
alert('trebuie sa selectezi o perioada mai mica de' + holidaysLeft + 'de zile');
}
}
}
});
}
}
;
}
;
return false;
});
$.ajax({
type: "GET",
url: location.protocol + '//' + location.host + "/rest/api/2/myself",
success: function (response) {
currentUser = $.parseJSON(response);
},
error: function (response) {
alert("Eroare" + response.result);
}
});
return false;
});
});
function calcBusinessDays(dDate1, dDate2) { // input given as Date objects
var iWeeks, iDateDiff, iAdjust = 0;
if (dDate2 < dDate1)
return -1; // error code if dates transposed
var iWeekday1 = dDate1.getDay(); // day of week
var iWeekday2 = dDate2.getDay();
iWeekday1 = (iWeekday1 === 0) ? 7 : iWeekday1; // change Sunday from 0 to 7
iWeekday2 = (iWeekday2 === 0) ? 7 : iWeekday2;
if ((iWeekday1 > 5) && (iWeekday2 > 5))
iAdjust = 1; // adjustment if both days on weekend
iWeekday1 = (iWeekday1 > 5) ? 5 : iWeekday1; // only count weekdays
iWeekday2 = (iWeekday2 > 5) ? 5 : iWeekday2;
// calculate differnece in weeks (1000mS * 60sec * 60min * 24hrs * 7 days = 604800000)
iWeeks = Math.floor((dDate2.getTime() - dDate1.getTime()) / 604800000);
if (iWeekday1 <= iWeekday2) {
iDateDiff = (iWeeks * 5) + (iWeekday2 - iWeekday1);
} else {
iDateDiff = ((iWeeks + 1) * 5) - (iWeekday1 - iWeekday2);
}
iDateDiff -= iAdjust // take into account both days on weekend
return (iDateDiff + 1); // add 1 because dates are inclusive
}
function parseDate(s) {
var lastSlash = s.lastIndexOf("/");
var years = s.substring(lastSlash + 1);
years = "20" + years;
s = s.replaceAt(lastSlash + 1, years);
var pattern = /(.*?)\/(.*?)\/(.*?)$/;
var result = s.replace(pattern, function (match, p1, p2, p3) {
var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul',
'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
return (months.indexOf(p2) + 1) + "/" + (p1) + "/" + p3;
});
return new Date(result);
}
String.prototype.replaceAt = function (index, character) {
return this.substr(0, index) + character + this.substr(index + character.length);
};
function propStopped(event) {
var msg = "";
if (event.isPropagationStopped()) {
msg = "called";
} else {
msg = "not called";
}
alert(msg);
}
Thanks.
Did you mean this?
Event.prototype.stopPropagation = function(){ alert('123') }
$('input').on('click',function(e){
e.stopPropagation();
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='button' value='click' />
From the question, it is unclear as to which code you control. I am reading between the lines that perhaps you control the function bound to the click event for the button, but you do not control the function bound to the focusout event, which is why you need to work around those calls.
If you want to control of execution of the events and make sure that yours happen first, it's possible to do this with something like jQuery.bindUp, just so long as the events are of the same type. In that way, you don't care if the other handler tries to call stopPropagation etc. because your handler will get to execute first anyway.
Given that, is it possible to restructure your code so that the logic you control (the part which needs to happen first!) is of the same event type as the existing event handler, and then use jQuery.bindUp to ensure that it gets executed before the event handler that you do not control? You can still bind to the click event if you need it, just so long as the dependent business logic is moved to the focusout event.
(If my assumptions are not correct, it would be helpful if you could update the question to describe the problem constraints in more detail.)
Related
I'm having trouble with JS code not executing on iPhone if I don't call alert before if statement. This is my code:
submitHandler = (e) => {
e.preventDefault();
var dataFromForm = $("#send").serialize();
alert(); // Without this the code below wont execute on iphne
if (window.localStorage) {
if (localStorage.getItem("timeout")) {
const timePrev = localStorage.getItem("timeout");
const timeNow = Math.round(new Date().getTime() / 1000);
if (timeNow - timePrev >= 300) {
var available = true;
} else {
var available = false;
document.getElementById("message").innerHTML =
'<span class="fail"> Spam protection</span>';
}
} else {
var available = true;
}
} else {
var available = true;
}
if (available) {
$.post("mail.php", dataFromForm, function (data) {
document.getElementById("message").innerHTML = "";
console.log(data);
data = JSON.parse(data);
console.log(data);
if (data.statusBool === true) {
document.getElementById("message").innerHTML =
'<span class="success">' + data.status + "</span>";
document.getElementById("name").value = "";
document.getElementById("email").value = "";
document.getElementById("msg").value = "";
var timenow = Math.round(new Date().getTime() / 1000);
localStorage.setItem("timeout", timenow);
} else {
document.getElementById("message").innerHTML =
'<span class="fail">' + data.status + "</span>";
}
});
}
setTimeout(function () {
document.getElementById("message").innerHTML = "";
}, 3000);
};
code below alert doesn't execute if I don't put alert before that statement.
Does anyone know how to solve this, or have an idea of what could I use instead of alert, so it's not visible for the user?
Answer by #Chris G
jsfiddle.net/rqht1kzo
localStorage.setItem('timeout', new Date().getTime() / 1000 - 400);
var available = false;
const timePrev = window.localStorage && window.localStorage.getItem('timeout');
if (timePrev) {
const timeNow = Math.round(new Date().getTime() / 1000);
if (timeNow - timePrev >= 300) available = true;
}
if (available) {
console.log("it's available")
} else {
document.getElementById('message').innerHTML = '<span class="fail"> fail message</span>';
}
I am having some issues trying to use the console to modify the time remaining on one site.
I want to be able to set the Time remaining to zero to be able to proceed to the next page.
I believe that the issue is that there are multiple things that need to be set in order to proceed to the next page.
See code below, any help you can provide would be appreciated.
var pageLoaded = 0;
var timerStatus = 'pending';
var secondsRemaining = -1;
var secondsElapsed = -1;
var startTicks = 0;
var errorCount = 0;
var estimatedSecondsRemaining = -1;
var zeroTimeCounter = 0;
var intervalIdUpdateBothTimers;
var nonLinearGuid = null;
$(document).ready(function() {
setInterval('AutoSave()', 120000);
intervalIdUpdateBothTimers = setInterval('UpdateBothTimers()', 1000);
if (timerStatus == 'pending') {
var totaltimeclock = document.getElementById('TotalTimeClock');
if (totaltimeclock != null) {
document.getElementById('TotalTimeClock').innerHTML = '-- \: -- \: --';
}
var timeremainingclock = document.getElementById('TimeRemainingClock');
if (timeremainingclock != null) {
document.getElementById('TimeRemainingClock').innerHTML = '-- \: -- \: --';
}
StartTimer();
}
});
function loaded(i,f) {
if (document.getElementById && document.getElementById(i) != null)
{
f();
}
else if (!pageLoaded) setTimeout('loaded(\''+i+'\','+f+')',100);
}
function SuspendTimer() {
UpdateBothTimers();
if (timerStatus == 'active') {
var data = "s=2&cp=" + this.location.pathname + "&nlg=" + GetNonLinearGuid();
timerStatus = 'suspended';
$.ajax({
type: "POST",
url: "/Courses/ajax/CourseData.aspx",
data: data,
success: displayTime,
async: false
});
clearInterval(intervalIdUpdateBothTimers);
}
}
function AutoSave()
{
if (timerStatus == 'active')
{
SaveTime();
}
}
function SaveTime()
{
var data = '';
if (typeof window.IsScormPage === 'undefined')
{
data = "cp=" + this.location.pathname + "&sp=false";
}
else
{
data = "cp=" + this.location.pathname + "&sp=true";
}
data += "&nlg=" + GetNonLinearGuid();
$.ajax({
type: "POST",
url: "/Courses/ajax/CourseData.aspx",
data: data,
success: displayTime,
async: false
});
}
function StartTimer()
{
timerStatus = 'active';
SetNonLinearGuid();
SaveTime();
}
// Sets the nonLinearGuid with the one in the DOM
// the GUID was generated in the server side and
// passed it to the client side (DOM)
function SetNonLinearGuid()
{
var $nonLinearGuid = $("#nonLinearGuid");
if ($nonLinearGuid === undefined)
{
$nonLinearGuid = $("input[name=nonLinearGuid]");
}
if ($nonLinearGuid.length)
{
nonLinearGuid = $nonLinearGuid.val() || null;
window.nonLinearGuid = window.nonLinearGuid || nonLinearGuid;
}
}
function GetNonLinearGuid() {
var nlg = (window.NonLinearGuid || nonLinearGuid),
admin = getQueryStringByName("admin", parent.window.location.href) || "";
if (admin.toLowerCase() == "d3v") {
printNonLinearGuid(nlg);
}
return nlg;
}
function getQueryStringByName(name, url) {
if (!url) url = window.location.href;
name = name.replace(/[\[\]]/g, '\\$&');
var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)'),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, ' '));
}
function displayTime(result)
{
if (result.isOk == false)
{
alert(result.message);
}
else
{
var d = new Date();
startTicks = d.getTime();
secondsRemaining = parseInt($(result).find("SecondsRemaining").text());
secondsElapsed = parseInt($(result).find("SecondsElapsed").text());
redirectUrl = $(result).find("RedirectUrl").text();
var suspendTimer = $(result).find("SuspendTimer").text();
var dataNonLinearGuid = "?nlg=" + GetNonLinearGuid();
if (redirectUrl != "") {
location.href = redirectUrl;
}
isError = $(result).find("Error").text();
if (isError == "true")
{
errorCount++;
if (errorCount > 3)
{
logout();
}
}
isOverworked = $(result).find("IsOverworked").text();
if (isOverworked == "true")
{
location.href = "/Courses/MyAccountNonLinear.aspx" + dataNonLinearGuid;
}
if (suspendTimer.length > 0) {
if ($.trim(suspendTimer).toLowerCase() == "true") {
SuspendTimer();
}
}
}
}
function logout()
{
window.top.location.href = "/Courses/loggedout.aspx";
}
function UpdateBothTimers() {
if (timerStatus != 'active') return;
if (secondsElapsed >= 0)
{
UpdateElapsedTimer();
//secondsElapsed++;
}
if (secondsRemaining >= 0) {
UpdateRemainingTimer();
}
if (estimatedSecondsRemaining <= 0 && zeroTimeCounter == 0) {
zeroTimeCounter++;
SaveTime();
}
}
var lang;
function qt(m,lng) {
$('#timeRemaining').css('display', 'none');
setTimeout("$('#EOMQuiz').submit();", m * 1000);
lang = lng;
setTimeout('updateQ('+ m +')', 1000);
}
function updateQ(m) {
--m;
var text;
if (lang == 'es') {
text = 'Entregar - ' + m + ' segundos restantes para completar la prueba';
}
else {
text = 'Submit - ' + m + ' seconds remaining to complete the quiz';
}
if (m > 0) {
setTimeout('updateQ('+m+')', 990);
}
else
{
$('#eomsubmitDiv').css('background-color', '#FF0000');
text ='Submitting... Please Wait.';
}
if (m <= 10 && m > 0)
{
if (m % 2 == 0)
{
$('#eomsubmitDiv').css('background-color', '#FFFF00');
}
else
{
$('#eomsubmitDiv').css('background-color', '#FFFFAA');
}
}
$('#eomsubmit').attr('value', text);
}
function UpdateElapsedTimer()
{
var s = secondsElapsed + (GetTickDiff()/1000);
UpdateTimer('TotalTimeClock', s, 'UP');
}
function GetTickDiff()
{
var d = new Date();
var tickDiff = d.getTime() - startTicks;
return tickDiff;
}
function UpdateRemainingTimer()
{
var s = secondsRemaining - (GetTickDiff()/1000);
estimatedSecondsRemaining = s;
if (s < 0) s = 0;
UpdateTimer('TimeRemainingClock', s, 'DOWN');
}
function UpdateTimer(ClockID,ElapsedSeconds,ClockDirection){
//check to see if we can run this code yet
if(document.getElementById && document.getElementById(ClockID) != null){
//declare vars
var _Seconds = 0;
var _Minutes = 0;
var _Hours = 0;
//Format Seconds
_Seconds = Math.floor(ElapsedSeconds % 60);
if(_Seconds <= 9) {
_Seconds = "0"+_Seconds;
}
//Format minutes
_Minutes = Math.floor(ElapsedSeconds/60 % 60);
if(_Minutes <= 9) {
_Minutes = "0"+_Minutes;
}
//Format hours
_Hours = Math.floor(ElapsedSeconds/3600 % 60);
if(_Hours <= 9){
_Hours = "0"+_Hours;
}
document.getElementById(ClockID).innerHTML = _Hours + ":" + _Minutes + ":" + _Seconds;
if (timerStatus != 'active')
{
setTimeout('UpdateTimer(\''+ClockID+'\','+ElapsedSeconds+',\''+ClockDirection+'\')',1000);
return;
}
if(ElapsedSeconds > 0 || ClockDirection == "UP"){
if(ClockDirection == "UP")
{
ElapsedSeconds = ElapsedSeconds + 1;
}
else
{
ElapsedSeconds = ElapsedSeconds - 1;
}
//setTimeout('UpdateTimer(\''+ClockID+'\','+ElapsedSeconds+',\''+ClockDirection+'\')',1000);
}
else{
//Timer has hit zero. Lets make sure the next buttons are visible.
$('#next_top').show();
$('#next_bot').show();
}
}
else if(!pageLoaded) //call function again in 100ms
{
//setTimeout('UpdateTimer(\''+ClockID+'\','+ElapsedSeconds+',\''+ClockDirection+'\')',100);
}
}
function DisplayNextButtons(){
$('#next_top').show();
$('#next_bot').show();
}
function hideNextButtons(){
$('#next_top').hide();
$('#next_bot').hide();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
I happened to stumble upon the same code. If you were on the same site as me,
I have a potential fix.
Instead of editing the time remaining I setup a script that will click next when the time has expired. I was too lazy to check whether they are checking timestamps server side. Also the server logs will look more similar to a regular user.
Instructions:
Download the following extension for Chrome
https://chrome.google.com/webstore/detail/custom-javascript-for-web/poakhlngfciodnhlhhgnaaelnpjljija?hl=en
Navigate to the site
click the CJS chrome extension button
check "enable cjs for this host"
paste the following JS snippet into the JS box
var t=setInterval(try_hit_next,1000);
function try_hit_next(){
if (estimatedSecondsRemaining <= 0)
window.location = $('#next_top').parent()[0]['href'];
}
click save
1) No needs to assign "setInterval" to a variable t
2) Has somebody tried to make fully automated script for this resource, i mean "driving defensive course" cause it pushes popups with personal questions randomly and besides shows pages with a сourse-related questions (constantly the same), so hope it's gonna be very useful "tool" )
Unfortunately the timers are actually being kept server-side. You can watch a POST to CourseData.aspx and it will return with new values for SecondsRemaining and SecondsElapsed. These new values are used to set the client-side timers. You can change the client side variables all you want but when you move to the next page, another call to CourseData.aspx is done to fetch the server time. So the server's timers rule this entire process.
I believe the only reason you see any JS timers is to provide a (now hidden) simple "time remaining" clock for the user.
However I am willing to bet that there's a way to POST a new time or SecondsRemaining to the CourseData.aspx page, I just don't know what set of post data variables might be needed to do so.
I'm using the Jcounter plugin http://devingredients.com/jcounter/ on a project, it's perfect for what I need, except for a problem I'm facing. I need it when I finish the countdown, it updates the same page only once, without giving infinite loop. How can I do this?
The callback function seems to give this possibilide, would I need some control? I have little experience in jquery.
<!DOCTYPE html>
<html>
<head>
<title>jCounter - jQuery plugin - devingredients.com</title>
<meta http-equiv="Content-Type" content="text/html;charset=ISO-8859-1">
<link rel="stylesheet" type="text/css" href="css/jquery.jCounter-iosl.css">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
<script type="text/javascript" src="js/jquery.jCounter-0.1.4.js"></script>
<script type="text/javascript">
$(document).ready(function() {
//first counter
$(".countdown1").jCounter({
animation: "slide",
date: "2017/10/13 19:53:20",
format: "dd:hh:mm:ss",
twoDigits: 'on',
callback: function() {
window.location.href = "index.php?block=Yes"
}
});
});
</script>
<div class="iosl-theme-wrapper countdown1">
<div class="iosl-theme">
<ul>
<li><p><span><em><b class="days">00</b><i class="daysSlider"><u>00</u><u>00</u></i></em></span></p></li>
<li><p><span><em><b class="hours">00</b><i class="hoursSlider"><u>00</u><u>00</u></i></em></span></p></li>
<li><p><span><em><b class="minutes">00</b><i class="minutesSlider"><u>00</u><u>00</u></i></em></span></p></li>
<li><p><span><em><b class="seconds">00</b><i class="secondsSlider"><u>00</u><u>00</u></i></em></span></p></li>
</ul>
<div class="jC-clear"></div>
<p class="jCtext">
<span><em class="textSeconds">SEGUNDOS</em></span>
<span><em class="textMinutes">MINUTOS</em></span>
<span><em class="textHours">HORAS</em></span>
<span><em class="textDays">DIAS</em></span>
</p>
<div class="jC-clear"></div>
</div>
</div>
**jquery.jCounter-0.1.4.js**
/**********************************
* jCounter Script v0.1.4 (beta)
* Author: Catalin Berta
* Official page and documentation: http://devingredients.com/jcounter
* Licensed under the MIT license
**********************************/
;(function($,document,window,undefined) {
//once upon a time...
$.fn.jCounter = function(options,callback) {
var jCounterDirection = 'down'; // points out whether it should count down or up | handled via customRange setting
var customRangeDownCount; //if true, it will tell countdown_proc() it's a down count and not an up count
var days,hours,minutes,seconds;
var endCounter = false; //stops jCounter if true
var eventDate; //time target (holds a number of seconds)
var pausedTime; //stores the time (in seconds) when pausing
var thisEl = this; //custom 'this' selector
var thisLength = this.length; //number of multiple elements per selector
var pluralLabels = new Array('DAYS','HOURS','MINUTES','SECONDS'); //plural labels - used for localization
var singularLabels = new Array('DAY','HOUR','MINUTE','SECOND'); //singular labels - used for localization
this.options = options; //stores jCounter's options parameter to verify against specified methods
this.version = '0.1.4';
//default settings
var settings = {
animation: null,
callback: null,
customDuration: null,
customRange: null,
date: null,
debugLog: false,
serverDateSource: 'dateandtime.php', //path to dateandtime.php file (i.e. http://my-domain.com/dateandtime.php)
format: 'dd:hh:mm:ss',
timezone: 'Europe/London',
twoDigits: 'on'
};
//merge the settings with the options values
if (typeof options === 'object') {
$.extend(settings,options);
thisEl.data("userOptions", settings); //push the settings to applied elements (they're used by methods)
}
if(thisEl.data('userOptions').debugLog == true && window['console'] !== undefined ) {
var consoleLog = true; //shows debug messages via console.log() if true
}
//METHODS
var jC_methods = {
//initialize
init : function() {
thisEl.each(function(i,el) {
initCounter(el);
});
},
//pause method: $.jCounter('pause')
pause : function() {
if(consoleLog) { console.log("(jC) Activity: Counter paused."); }
endCounter = true;
return thisEl.each(function(i,el) {
clearInterval($(el).data("jC_interval"));
});
},
//stop method: $.jCounter('stop')
stop : function() {
if(consoleLog) { console.log("(jC) Activity: Counter stopped."); }
endCounter = true;
return thisEl.each(function(i,el) {
clearInterval($(el).data("jC_interval"));
$(el).removeData("jC_pausedTime");
resetHTMLCounter(el);
});
},
//reset method: $.jCounter('reset')
reset : function() {
if(consoleLog) { console.log("(jC) Activity: Counter reset."); }
return thisEl.each(function(i,el) {
clearInterval($(el).data("jC_interval"));
resetHTMLCounter(el);
initCounter(el);
});
},
//start method: $.jCounter('start')
start : function() {
if(consoleLog) { console.log("(jC) Activity: Counter started."); }
return thisEl.each(function(i,el) {
pausedTime = $(el).data("jC_pausedTime");
endCounter = false;
clearInterval($(el).data("jC_interval"));
initCounter(el);
});
}
}
//checks whether customDuration is used
if(thisEl.data("userOptions").customDuration) {
if(!isNaN(thisEl.data("userOptions").customDuration)) {
var customDuration = true;
} else {
var customDuration = false;
if(consoleLog) { console.log("(jC) Error: The customDuration value is not a number! NOTE: 'customDuration' accepts a number of seconds."); }
}
}
//checks whether customRange is used
if(thisEl.data("userOptions").customRange) {
var customRangeValues = thisEl.data("userOptions").customRange.split(":");
var rangeVal0 = parseInt(customRangeValues[0]);
var rangeVal1 = parseInt(customRangeValues[1]);
if(!isNaN(rangeVal0) && !isNaN(rangeVal1)) {
var customRange = true;
if(rangeVal0 > rangeVal1) {
var customRangeDownCount = true;
} else {
var customRangeDownCount = false;
jCounterDirection = 'up';
}
} else {
var customRange = false;
if(consoleLog) { console.log("(jC) Error: The customRange value is not a valid range! Example: customRange: '0:30' or '30:0'"); }
}
}
//checks whether animation is set to slide
if(thisEl.data("userOptions").animation == 'slide') {
thisEl.data("jCanimation","slide");
}
//FUNCTIONS
//jCounter initializer
function initCounter(el) {
if(customDuration) {
if (pausedTime) {
if (!isNaN(pausedTime)) {
eventDate = Math.round(pausedTime);
}
} else {
eventDate = Math.round($(el).data("userOptions").customDuration);
}
currentTime = 0;
countdown_proc(currentTime,el);
$(el).data("jC_interval", setInterval(function(){
if(endCounter == false) {
currentTime = parseInt(currentTime) + 1;
countdown_proc(currentTime,el)
}
},1000));
} else if(customRange) {
eventDate = Math.round(customRangeValues[1]);
if (pausedTime) {
if (!isNaN(pausedTime)) {
var currentTime = eventDate - pausedTime;
}
} else {
var currentTime = Math.round(customRangeValues[0]);
}
countdown_proc(currentTime,el);
$(el).data("jC_interval", setInterval(function(){
if(endCounter == false) {
var ifRangeDownCount = (customRangeDownCount) ? currentTime = parseInt(currentTime) - 1 : currentTime = parseInt(currentTime) + 1;
countdown_proc(currentTime,el);
}
},1000));
} else {
eventDate = Date.parse($(el).data("userOptions").date) / 1000;
dateSource = thisEl.data("userOptions").serverDateSource + '?timezone=' + thisEl.data("userOptions").timezone + '&callback=?';
$.ajax({
url: dateSource,
dataType : 'json',
data : {},
success : function(data, textStatus){
var currentDate = Date.parse(data.currentDate) / 1000;
startCounter(currentDate,el);
},
error : function(){
if(consoleLog) { console.log("(jC) Error: Couldn't find dateandtime.php from serverDateSource: " + thisEl.data('userOptions').serverDateSource + "\n(jC) - Make sure the path is correct! \n(jC) - Now using the client-side time (not recommended).") }
var currentDate = Math.floor($.now() / 1000);
startCounter(currentDate,el);
}
});
}
}
function startCounter(currentDate,el) {
countdown_proc(currentDate,el);
if (eventDate > currentDate) {
$(el).data("jC_interval", setInterval(function(){
if(endCounter == false) {
currentDate = parseInt(currentDate) + 1;
countdown_proc(currentDate,el)
}
},1000));
} else {
resetHTMLCounter(el)
}
}
//jCslider - adds the slide effect layer
//Note: this requires a jCounter slide-ready theme! (i.e. iOS dark or iOS light)
function jCslider(el,unitClass,timeUnit,eventDate,duration) {
$(el).find(unitClass + " u").each(function(i,el) {
var twoDigits = (thisEl.data("userOptions").twoDigits == 'on') ? '0' : '';
var newIndex = (jCounterDirection == 'up') ? newIndex = -i : newIndex = i;
currNo = parseInt(timeUnit,10) + (newIndex);
if (String(parseInt(timeUnit,10)).length >= 2) {
$(el).text(parseInt(timeUnit,10) + (newIndex))
} else if(String(parseInt(timeUnit,10)).length == 1 && currNo == 10) {
$(el).text(parseInt(timeUnit,10) + (newIndex))
} else {
$(el).text(twoDigits + (parseInt(timeUnit,10) + (newIndex)));
}
})
$(el).find(unitClass).animate({
top: '0.15em'
},200, function() {
$(el).find(unitClass + " u:eq(1)").remove();
$(el).find(unitClass).prepend('<u></u>');
$(el).find(unitClass).css({'top':'-1.24em'})
});
}
//resets jCounter's HTML values to 0 or 00, based on the twoDigits setting
function resetHTMLCounter(el) {
if(thisEl.data("userOptions").twoDigits == 'on') {
$(el).find(".days,.hours,.minutes,.seconds").text('00');
} else if(thisEl.data("userOptions").twoDigits == 'off') {
$(el).find(".days,.hours,.minutes,.seconds").text('0');
}
if(thisEl.data("jCanimation") == 'slide') {
$(el).find(".daysSlider u,.hoursSlider u,.minutesSlider u,.secondsSlider u").text('00');
}
}
//main jCounter processor
function countdown_proc(duration,el) {
//check if the counter needs to count down or up
if(customRangeDownCount) {
if(eventDate >= duration) {
clearInterval($(el).data("jC_interval"));
if(thisEl.data("userOptions").callback) {
thisEl.data("userOptions").callback.call(this);
}
}
} else {
if(eventDate <= duration) {
clearInterval($(el).data("jC_interval"));
if(thisEl.data("userOptions").callback) {
thisEl.data("userOptions").callback.call(this);
}
}
}
//if customRange is used, update the seconds variable
var seconds = (customRange) ? duration : eventDate - duration;
var thisInstanceFormat = thisEl.data("userOptions").format;
//calculate seconds into days,hours,minutes,seconds
//if dd (days) is specified in the format setting (i.e. format: 'dd:hh:mm:ss')
if(thisInstanceFormat.indexOf('dd') != -1) {
var days = Math.floor(seconds / (60 * 60 * 24)); //calculate the number of days
seconds -= days * 60 * 60 * 24; //update the seconds variable with no. of days removed
}
//if hh (hours) is specified
if(thisInstanceFormat.indexOf('hh') != -1) {
var hours = Math.floor(seconds / (60 * 60));
seconds -= hours * 60 * 60; //update the seconds variable with no. of hours removed
}
//if mm (minutes) is specified
if(thisInstanceFormat.indexOf('mm') != -1) {
var minutes = Math.floor(seconds / 60);
seconds -= minutes * 60; //update the seconds variable with no. of minutes removed
}
//if ss (seconds) is specified
if(thisInstanceFormat.indexOf('ss') == -1) {
seconds -= seconds; //if ss is unspecified in format, update the seconds variable to 0;
}
//conditional Ss
//updates the plural and singular labels accordingly
if (days == 1) { $(el).find(".textDays").text(singularLabels[0]); } else { $(el).find(".textDays").text(pluralLabels[0]); }
if (hours == 1) { $(el).find(".textHours").text(singularLabels[1]); } else { $(el).find(".textHours").text(pluralLabels[1]); }
if (minutes == 1) { $(el).find(".textMinutes").text(singularLabels[2]); } else { $(el).find(".textMinutes").text(pluralLabels[2]); }
if (seconds == 1) { $(el).find(".textSeconds").text(singularLabels[3]); } else { $(el).find(".textSeconds").text(pluralLabels[3]); }
//twoDigits ON setting
//if the twoDigits setting is set to ON, jCounter will always diplay a minimum number of 2 digits
if(thisEl.data("userOptions").twoDigits == 'on') {
days = (String(days).length >= 2) ? days : "0" + days;
hours = (String(hours).length >= 2) ? hours : "0" + hours;
minutes = (String(minutes).length >= 2) ? minutes : "0" + minutes;
seconds = (String(seconds).length >= 2) ? seconds : "0" + seconds;
}
//updates the jCounter's html values
if(!isNaN(eventDate)) {
$(el).find(".days").text(days);
$(el).find(".hours").text(hours);
$(el).find(".minutes").text(minutes);
$(el).find(".seconds").text(seconds);
if(thisEl.data("jCanimation") == 'slide') {
$(el).find(".daysSlider u:eq(1)").text(days);
$(el).find(".hoursSlider u:eq(1)").text(hours);
$(el).find(".minutesSlider u:eq(1)").text(minutes);
$(el).find(".secondsSlider u:eq(1)").text(seconds);
jCslider(el,'.secondsSlider',seconds,eventDate,duration);
if(parseInt(seconds,10) == 59) {
jCslider(el,'.minutesSlider',minutes,eventDate,duration)
if(parseInt(minutes,10) == 59) {
jCslider(el,'.hoursSlider',hours,eventDate,duration)
if(parseInt(hours,10) == 23) {
jCslider(el,'.daysSlider',days,eventDate,duration)
}
}
}
}
} else {
if(consoleLog) { console.log("(jC) Error: Invalid date! Here's an example: 01 January 1970 12:00:00"); }
clearInterval($(el).data("jC_interval"));
}
//stores the remaining time when pausing jCounter
$(el).data("jC_pausedTime", eventDate-duration);
}
//method calling logic
if ( jC_methods[this.options] ) {
return jC_methods[ this.options ].apply( this, Array.prototype.slice.call( arguments, 1 ));
} else if ( typeof this.options === 'object' || ! this.options ) {
return jC_methods.init.apply( this, arguments );
} else {
console.log('(jC) Error: Method >>> ' + this.options + ' <<< does not exist.' );
}
}
//the end;
}) (jQuery,document,window);
I'm using this Calendar, and "i'm forced to use it" and i'm wondering if you could help me sorting out a small issue i'm having.
Calendar: http://www.bulgaria-web-developers.com/projects/javascript/calendar/
I have 2 input fields that this calendar is on,
<input type="text" id="cr_date_from" />
<input type="text" id="cr_date_to" />
And after selecting the date in "date_from" i need it to jump to "date_to" and have the same date as selected in the date_from field. As this will not cause confusion when people are selecting a date months ahead in time, and not to scroll all the way to that date in the date_to as well...
I've tried researching on this for a while now without luck, so i'm hoping you guys are able to help me out..
Appreciate all help on this!
Here is also the javascript for those interested...
bindSearch: function () {
var self = this,
dateFrom = new Calendar({
element: "cr_date_from",
//dateFormat: "Y-m-d",
dateFormat: self.opts.dateFormat,
monthNamesFull: self.opts.monthNamesFull,
dayNames: self.opts.dayNames,
disablePast: true,
months: 3,
onSelect: function () {
reCalc.call(self);
}
}),
dateTo = new Calendar({
element: "cr_date_to",
//dateFormat: "Y-m-d",
dateFormat: self.opts.dateFormat,
monthNamesFull: self.opts.monthNamesFull,
dayNames: self.opts.dayNames,
disablePast: true,
months: 3,
onSelect: function () {
reCalc.call(self);
}
}),
lnkFrom = document.getElementById("crDateFrom"),
lnkTo = document.getElementById("crDateTo"),
btnQuote = document.getElementById("crBtnQuote"),
btnMap = document.getElementById("crBtnMap"),
sameLoc = document.getElementById("cr_same_location"),
returnLoc = document.getElementById("crReturnBox");
self.elFrom = document.getElementById("cr_date_from");
self.elTo = document.getElementById("cr_date_to");
self.elHFrom = document.getElementById("cr_hour_from");
self.elMFrom = document.getElementById("cr_minutes_from");
self.elHTo = document.getElementById("cr_hour_to");
self.elMTo = document.getElementById("cr_minutes_to");
function reCalc() {
var from = Date.parseExact(this.elFrom.value, dateFormat(self.opts.dateFormat, 'datejs')).getTime() + (parseInt(this.elHFrom.value, 10) * 3600000) + (parseInt(this.elMFrom.value, 10) * 60000),
to = Date.parseExact(this.elTo.value, dateFormat(self.opts.dateFormat, 'datejs')).getTime() + (parseInt(this.elHTo.value, 10) * 3600000) + (parseInt(this.elMTo.value, 10) * 60000),
nd = document.getElementById("crNumDays"),
days;
if (from !== null && to !== null) {
days = Math.ceil((to - from) / 86400000);
if (days > 0) {
nd.lastChild.innerHTML = days;
nd.style.display = "";
} else {
nd.style.display = "none";
}
} else {
nd.style.display = "none";
}
}
if (lnkFrom) {
lnkFrom.onclick = function (e) {
if (e && e.preventDefault) {
e.preventDefault();
}
dateFrom.isOpen ? dateFrom.close() : dateFrom.open();
return false;
};
}
if (lnkTo) {
lnkTo.onclick = function (e) {
if (e && e.preventDefault) {
e.preventDefault();
}
dateTo.isOpen ? dateTo.close() : dateTo.open();
return false;
};
}
if (btnMap) {
btnMap.onclick = function (e) {
self.overlayMap.open();
if (e && e.preventDefault) {
e.preventDefault();
}
return false;
}
}
if (sameLoc && returnLoc) {
function bindLoc(el) {
if (this.checked) {
el.style.display = "none";
} else {
el.style.display = "";
}
}
sameLoc.onchange = function () {
bindLoc.call(this, returnLoc);
};
sameLoc.onclick = function () {
bindLoc.call(this, returnLoc);
};
}
if (btnQuote) {
btnQuote.onclick = function () {
this.disabled = true;
if (!self.validateSearch(this)) {
this.disabled = false;
return;
}
self.passed.first = true;
self.loadCars.apply(self, [JABB.Utils.serialize(document.getElementById("crFormSearch"))]);
};
}
},
The question is very simple but also a bit theoretical.
Let's imagine you have a long JQuery script which modifies and animate the graphics of the web site. It's objective is to handle the UI. The UI has to be responsive so the real need for this JQuery is to mix some state of visualization (sportlist visible / not visible) with some need due to Responsive UI.
Thinking from an MVC / AngularJS point of view. How should a programmer handle that?
How to refactor JS / JQuery code to implement separation of concerns described by MVC / AngularJS?
I provide an example of JQuery code to speak over something concrete.
$.noConflict();
jQuery(document).ready(function ($) {
/*variables*/
var sliderMenuVisible = false;
/*dom object variables*/
var $document = $(document);
var $window = $(window);
var $pageHost = $(".page-host");
var $sportsList = $("#sports-list");
var $mainBody = $("#mainBody");
var $toTopButtonContainer = $('#to-top-button-container');
/*eventHandlers*/
var displayError = function (form, error) {
$("#error").html(error).removeClass("hidden");
};
var calculatePageLayout = function () {
$pageHost.height($(window).height());
if ($window.width() > 697) {
$sportsList.removeAttr("style");
$mainBody
.removeAttr("style")
.unbind('touchmove')
.removeClass('stop-scroll');
if ($(".betslip-access-button")[0]) {
$(".betslip-access-button").fadeIn(500);
}
sliderMenuVisible = false;
} else {
$(".betslip-access-button").fadeOut(500);
}
};
var formSubmitHandler = function (e) {
var $form = $(this);
// We check if jQuery.validator exists on the form
if (!$form.valid || $form.valid()) {
$.post($form.attr("action"), $form.serializeArray())
.done(function (json) {
json = json || {};
// In case of success, we redirect to the provided URL or the same page.
if (json.success) {
window.location = json.redirect || location.href;
} else if (json.error) {
displayError($form, json.error);
}
})
.error(function () {
displayError($form, "Login service not available, please try again later.");
});
}
// Prevent the normal behavior since we opened the dialog
e.preventDefault();
};
//preliminary functions//
$window.on("load", calculatePageLayout);
$window.on("resize", calculatePageLayout);
//$(document).on("click","a",function (event) {
// event.preventDefault();
// window.location = $(this).attr("href");
//});
/*evet listeners*/
$("#login-form").submit(formSubmitHandler);
$("section.navigation").on("shown hidden", ".collapse", function (e) {
var $icon = $(this).parent().children("button").children("i").first();
if (!$icon.hasClass("icon-spin")) {
if (e.type === "shown") {
$icon.removeClass("icon-caret-right").addClass("icon-caret-down");
} else {
$icon.removeClass("icon-caret-down").addClass("icon-caret-right");
}
}
toggleBackToTopButton();
e.stopPropagation();
});
$(".collapse[data-src]").on("show", function () {
var $this = $(this);
if (!$this.data("loaded")) {
var $icon = $this.parent().children("button").children("i").first();
$icon.removeClass("icon-caret-right icon-caret-down").addClass("icon-refresh icon-spin");
console.log("added class - " + $icon.parent().html());
$this.load($this.data("src"), function () {
$this.data("loaded", true);
$icon.removeClass("icon-refresh icon-spin icon-caret-right").addClass("icon-caret-down");
console.log("removed class - " + $icon.parent().html());
});
}
toggleBackToTopButton();
});
$("#sports-list-button").on("click", function (e)
{
if (!sliderMenuVisible)
{
$sportsList.animate({ left: "0" }, 500);
$mainBody.animate({ left: "85%" }, 500)
.bind('touchmove', function (e2) { e2.preventDefault(); })
.addClass('stop-scroll');
$(".betslip-access-button").fadeOut(500);
sliderMenuVisible = true;
}
else
{
$sportsList.animate({ left: "-85%" }, 500).removeAttr("style");
$mainBody.animate({ left: "0" }, 500).removeAttr("style")
.unbind('touchmove').removeClass('stop-scroll');
$(".betslip-access-button").fadeIn(500);
sliderMenuVisible = false;
}
e.preventDefault();
});
$mainBody.on("click", function (e) {
if (sliderMenuVisible) {
$sportsList.animate({ left: "-85%" }, 500).removeAttr("style");
$mainBody.animate({ left: "0" }, 500)
.removeAttr("style")
.unbind('touchmove')
.removeClass('stop-scroll');
$(".betslip-access-button").fadeIn(500);
sliderMenuVisible = false;
e.stopPropagation();
e.preventDefault();
}
});
$document.on("click", "div.event-info", function () {
if (!sliderMenuVisible) {
var url = $(this).data("url");
if (url) {
window.location = url;
}
}
});
function whatDecimalSeparator() {
var n = 1.1;
n = n.toLocaleString().substring(1, 2);
return n;
}
function getValue(textBox) {
var value = textBox.val();
var separator = whatDecimalSeparator();
var old = separator == "," ? "." : ",";
var converted = parseFloat(value.replace(old, separator));
return converted;
}
$(document).on("click", "a.selection", function (e) {
if (sliderMenuVisible) {
return;
}
var $this = $(this);
var isLive = $this.data("live");
var url = "/" + _language + "/BetSlip/Add/" + $this.data("selection") + "?odds=" + $this.data("odds") + "&live=" + isLive;
var urlHoveringBtn = "/" + _language + '/BetSlip/AddHoveringButton/' + $this.data("selection") + "?odds=" + $this.data("odds") + "&live=" + isLive;
$.ajax(urlHoveringBtn).done(function (dataBtn) {
if ($(".betslip-access-button").length == 0 && dataBtn.length > 0) {
$("body").append(dataBtn);
}
});
$.ajax(url).done(function (data) {
if ($(".betslip-access").length == 0 && data.length > 0) {
$(".navbar").append(data);
$pageHost.addClass("betslipLinkInHeader");
var placeBetText = $("#live-betslip-popup").data("placebettext");
var continueText = $("#live-betslip-popup").data("continuetext");
var useQuickBetLive = $("#live-betslip-popup").data("usequickbetlive").toLowerCase() == "true";
var useQuickBetPrematch = $("#live-betslip-popup").data("usequickbetprematch").toLowerCase() == "true";
if ((isLive && useQuickBetLive) || (!isLive && useQuickBetPrematch)) {
var dialog = $("#live-betslip-popup").dialog({
modal: true,
dialogClass: "fixed-dialog"
});
dialog.dialog("option", "buttons", [
{
text: placeBetText,
click: function () {
var placeBetUrl = "/" + _language + "/BetSlip/QuickBet?amount=" + getValue($("#live-betslip-popup-amount")) + "&live=" + $this.data("live");
window.location = placeBetUrl;
}
},
{
text: continueText,
click: function () {
dialog.dialog("close");
}
}
]);
}
}
if (data.length > 0) {
$this.addClass("in-betslip");
}
});
e.preventDefault();
});
$(document).on("click", "a.selection.in-betslip", function (e) {
if (sliderMenuVisible) {
return;
}
var $this = $(this);
var isLive = $this.data("live");
var url = "/" + _language + "/BetSlip/RemoveAjax/" + $this.data("selection") + "?odds=" + $this.data("odds") + "&live=" + isLive;
$.ajax(url).done(function (data) {
if (data.success) {
$this.removeClass("in-betslip");
if (data.selections == 0) {
$(".betslip-access").remove();
$(".betslip-access-button").remove();
$(".page-host").removeClass("betslipLinkInHeader");
}
}
});
e.preventDefault();
});
$("section.betslip .total-stake button.live-betslip-popup-plusminus").click(function (e) {
if (sliderMenuVisible) {
return;
}
e.preventDefault();
var action = $(this).data("action");
var amount = parseFloat($(this).data("amount"));
if (!isNumeric(amount)) amount = 1;
var totalStake = $("#live-betslip-popup-amount").val();
if (isNumeric(totalStake)) {
totalStake = parseFloat(totalStake);
} else {
totalStake = 0;
}
if (action == "decrease") {
if (totalStake < 1.21) {
totalStake = 1.21;
}
totalStake -= amount;
} else if (action == "increase") {
totalStake += amount;
}
$("#live-betslip-popup-amount").val(totalStake);
});
toggleBackToTopButton();
function toggleBackToTopButton() {
isScrollable() ? $toTopButtonContainer.show() : $toTopButtonContainer.hide();
}
$("#to-top-button").on("click", function () { $("#mainBody").animate({ scrollTop: 0 }); });
function isScrollable() {
return $("section.navigation").height() > $(window).height() + 93;
}
var isNumeric = function (string) {
return !isNaN(string) && isFinite(string) && string != "";
};
function enableQuickBet() {
}
});
My steps in such cases are:
First of all write (at least) one controller
Replace all eventhandler with ng-directives (ng-click most of all)
Pull the view state out of the controller with ng-style and ng-class. In most of all cases ng-show and ng-hide will be sufficed
If there is code that will be used more than once, consider writing a directive.
And code that has nothing todo with the view state - put the code in a service
write unit tests (i guess there is no one until now:) )