Swipe not working when added dynamically via AJAX - javascript

Background:
Page B is dynamically loaded in Page A by XMLHttpRequest. Page B contains list of name which on swipe reloads Page B itself.
Issue:
When Page A is loaded swipe is working fine, but when Page B reloads, Swipe functionality fails to function.
Tried with swipe.js in Page B as well but nothing seems to work.
Would be great help if anyone could point out issue... Thanks
Code
Page A:
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<script>
var d = '<?php echo $result["d_delayed"]; ?>';
var q = '<?php echo $result["d_queued"]; ?>';
if(typeof(EventSource) !== "undefined") {
var source = new EventSource("detect_change");
source.onmessage = function(event) {
var obj = JSON.parse(event.data);
// Reload on Queue Update
document.getElementById("title_change").innerHTML = obj.name;
if(d != obj.delay || q != obj.queue){
loadDoc("");
}
};
}
</script>
<div>
<p id="demo"></p>
</div>
<script>
//Load through XMLHttpRequest
function loadDoc(search) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
xhttp.open("GET", "swipe_page.php", true);
xhttp.send();
}
loadDoc(search);
</script>
</body>
</html>
Page B (swipe_page.php)
<ul class="list-group list-group-flush patient-list swipe-list bottom-pad-ul">
<li class="list-group-item">
<div class="patient-list__info swipe swipe-left-right" linkRight="#link" linkLeft="#link">
<a data-toggle="modal" class="bg-hov" data-target="#myModal"><span class="span-left-arrow"><i class="fa fa-chevron-left float-left" aria-hidden="true"></i></span></a>
<span class="patient-list__patient-name">User Name</span>
<a data-toggle="modal" data-target="#myModal"><span class="badge badge-light badge-pill patient-list__patient-badge patient-list__patient-badge--first">number</span></a>
</div>
<div class="patient-list__info patient-list__info--mirror" style="">
<i class="fa fa-reply" aria-hidden="true"></i>&nbsp&nbspUndo
</div>
</li>
</ul>
Swipe script
var s1 = Swiped.init({
query: 'li>.swipe-right',
list: false,
left: 5,
right: 0
});
var s2 = Swiped.init({
query: 'li>.swipe-left-right',
list: false,
left: 5,
right: 5
});
jQuery(document).on('touchstart', 'li>.swipe-right', function() {
s1.open;
});
jQuery(document).on('touchstart', 'li>.swipe-left-right', function() {
s2.open;
});
var onOpenfunction = function() {
var clickUndo = false;
var dir = this.dir;
var offset, invert_offser;
//jQuery(this.elem).css('transform', 'translate3d(0px, 0px, 0px)');
if (dir === 1) {
offset = '110%';
invert_offser = '-110%';
} else {
offset = '-110%';
invert_offser = '110%';
}
jQuery(this.elem).animate({left: offset});
console.log(offset);
jQuery('.patient-list__info--mirror',jQuery(this.elem).parent()).css('left',invert_offser).animate({left: 0});
jQuery('.patient-list__info--mirror',jQuery(this.elem).parent()).click(function () {
jQuery('.patient-list__info',jQuery(this).parent()).not('.patient-list__info--mirror').animate({left: 0});
jQuery(this).animate({left: invert_offser});
clickUndo = true;
jQuery(this).off();
});
var currentElem = this.elem;
var parentElem = jQuery(this.elem).parent();
setTimeout(function() {
if(!clickUndo) {
jQuery(parentElem).hide();
if(dir === 1){
console.log(jQuery(currentElem).attr('linkRight'));
var right_swipe = jQuery(currentElem).attr('linkRight');
$.ajax({url: right_swipe, success: function(result){
}});
} else {
console.log(jQuery(currentElem).attr('linkLeft'));
var left_swipe = jQuery(currentElem).attr('linkLeft');
$.ajax({url: left_swipe, success: function(result){
}});
}
}
}, 5000);
};
Swiped.init({
query: 'ul.swipe-list>li>.swipe-left-right',
onOpen: onOpenfunction
});
Swiped.init({
query: 'ul.swipe-list>li>.swipe-right',
onOpen: onOpenfunction
});

Finally I have figured out the underlying issue. As Page B is loaded by Ajax each time, Swipe script is not loaded.
All you have to do is load the swipe script each time when Page B is loaded.
Hope this helps save time for someone!!!

Related

How to show two charts in the same html page

I'm working on a project where I should show two kind of charts :
a Real time Chart and I'm using smoothie.js lib for this.
a normal chart with zoom option and I'm using canvas lib for this.
as it showen in the code below the smoothie.js use on the body tag an "onload" :
<!DOCTYPE html>
<meta charset="utf-8">
<html>
<head>
<title>Pression en temps réel</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script type="text/javascript" src="smoothie.js"></script>
<script type="text/javascript" src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
<script type="text/javascript">
window.bufferX = [];
setInterval(function () {
if( typeof lastid == 'undefined' ) {
$.get( "../be.php/lastid_1", function( dataA ) {
lastid = dataA[0].id_x+1;
})
}
else {
$.get( "../be.php/1&"+lastid, function( dataB ) {
var i =0;
var j=0;
if( typeof counter == 'undefined' ) {
counter = 0;
}
if( typeof pck_prev == 'undefined' ) {
pck_prev = -1;
}
lastid = dataB[0].last_id;
for(i=0;i<dataB.length;i++) {
for(j=0;j<dataB[i].data.length;j++) {
if(dataB[i].data[j] !== "" && dataB[i].data[j] !== 0 && typeof dataB[i].data[j] !== 'undefined' && pck_prev !== dataB[i].pck) {
window.bufferX.push(dataB[i].data[j]);
}
}
pck_prev = dataB[i].pck;
}
if(typeof window.bufferX[counter] == 'undefined') {
data_p.append(new Date().getTime(), window.bufferX[counter-1]);
}
})
}
},3000);
var data_p = new TimeSeries();
setInterval(function() {
if(window.bufferX.length>50 && counter <window.bufferX.length)
{
if( typeof counter == 'undefined' ) {
counter = 0;
}
else {
data_p.append(new Date().getTime(), window.bufferX[counter]);
counter++;
}
}
}, 250);
function createTimeline() {
var chart = new SmoothieChart({responsive: true});
chart.addTimeSeries(data_p, { strokeStyle: 'rgba(0, 255, 0, 1)', fillStyle: 'rgba(0, 255, 0, 0.2)', lineWidth: 4 });
chart.streamTo(document.getElementById("chart"), 250);
}
</script>
<script type="text/javascript">
window.onload = function () {
var chart = new CanvasJS.Chart("chartContainer",
{
zoomEnabled: true,
title:{
text: "Try Zooming And Panning"
},
axisY:{
includeZero: false
},
data: data, // random generator below
});
chart.render();
}
var limit = 1000; //increase number of dataPoints by increasing this
var y = 0;
var data = []; var dataSeries = { type: "line" };
var dataPoints = [];
for (var i = 0; i < limit; i += 1) {
y += (Math.random() * 10 - 5);
dataPoints.push({
x: i - limit / 2,
y: y
});
}
dataSeries.dataPoints = dataPoints;
data.push(dataSeries);
</script>
</head>
<body onload="createTimeline()">
<canvas id="chart" style="width:100%; height:700px;"></canvas>
<div id="chartContainer" style="height: 700px; width: 100%;">
</div>
</body>
</html>
The problem is if I delete onload from body tag I will get the canvas chart only and if I let it I will get the real time chart only.
I would like to have both charts showen on my page.
Thanks for reading.
window.onload and <body onload="yourfunction();"> are different ways of using the same event and you are using both which is causing the issue. The easiest way to fix this problem is that you should write both the implementation in one event either in window.onload or in onload of body tag.
Find the updated fiddle here.
You can find both the chart are visible at the same time.

Jquery custom images slider only works once or the third time

I'm trying to create a simple images slider. The problem I'm facing is that the next and prev buttons only work the first time. Then when you hover an item again it doesn't work. When you hover an item the third time it works, and so on.
I just can't find what's causing this behaviour.
Here's a working fiddle
$('.item.with-sec-image').on('mouseenter', function() {
var $this = $(this);
/* load data only once */
if (!$this.hasClass('images-initialized')) {
var url = $this.data('handle').replace('.html', '.ajax');
var purl = $this.data('handle');
$.getJSON(url, function(data) {
if (data.images.length > 1) {
var slider = $this.find('.slider');
if (data.images.length >= 2 && data.images.length != slider.find('li.selected').length) {
$.each(data.images, function(index, image) {
var img_url = image.replace('50x50x2', '400x400x2')
if (slider.find('li.selected').data('index') != index) {
var $newImage = $('<li><img src="' + img_url + '" /></li>')
slider.append($newImage);
}
});
}
}
}).done(function() {
$this.addClass('images-initialized');
});
}
$this.on('click', '.slider-btn', function() {
updateSlider($this)
});
});
The function to update the slider
function updateSlider(navigation) {
var $this = navigation
var sliderContainer = $this.find('.images .slider'),
activeSlider = sliderContainer.children('.selected').removeClass('selected');
if ($this.hasClass('next')) {
(!activeSlider.is(':last-child')) ? activeSlider.next().addClass('selected'): sliderContainer.children('li').eq(0).addClass('selected');
} else {
(!activeSlider.is(':first-child')) ? activeSlider.prev().addClass('selected'): sliderContainer.children('li').last().addClass('selected');
}
}
And, this is my HTML:
<div class="item with-sec-image" data-handle="some-url">
<div class="images">
<ul class="slider">
<li data-index="0" class="selected"><img src="link-to-image" /></li>
</ul>
<ul class="slider-navigation">
<li class="prev btn-round slider-btn small"><i class="icon-left"></i></li>
<li class="next btn-round slider-btn small"><i class="icon-right"></i></li>
</ul>
</div>
</div>
$('.item.with-sec-image').on('mouseenter', function() {
var $this = $(this);
/* load data only once */
if (!$this.hasClass('images-initialized')) {
var url = $this.data('handle').replace('.html', '.ajax');
var purl = $this.data('handle');
$.getJSON(url, function(data) {
if (data.images.length > 1) {
var slider = $this.find('.slider');
if (data.images.length >= 2 && data.images.length != slider.find('li.selected').length) {
$.each(data.images, function(index, image) {
var img_url = image.replace('50x50x2', '400x400x2')
if (slider.find('li.selected').data('index') != index) {
var $newImage = $('<li><img src="' + img_url + '" /></li>')
slider.append($newImage);
}
});
}
}
}).done(function() {
$this.addClass('images-initialized');
});
}
$this.on('click', '.slider-btn', function() {
updateSlider($this)
});
});
// The function to update the slider
function updateSlider(navigation) {
var $this = navigation
var sliderContainer = $this.find('.images .slider'),
activeSlider = sliderContainer.children('.selected').removeClass('selected');
if ($this.hasClass('next')) {
(!activeSlider.is(':last-child')) ? activeSlider.next().addClass('selected'): sliderContainer.children('li').eq(0).addClass('selected');
} else {
(!activeSlider.is(':first-child')) ? activeSlider.prev().addClass('selected'): sliderContainer.children('li').last().addClass('selected');
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="item with-sec-image" data-handle="some-url">
<div class="images">
<ul class="slider">
<li data-index="0" class="selected"><img src="link-to-image" /></li>
</ul>
<ul class="slider-navigation">
<li class="prev btn-round slider-btn small"><i class="icon-left"></i></li>
<li class="next btn-round slider-btn small"><i class="icon-right"></i></li>
</ul>
</div>
</div>
Ok i figured out the problem.
your are binding the click event on mouseenter which mean that it will be bind many time. so one click will equal multiple clicks and that why you are encountering this behavior.
I have made small changes to your code look below. and also here is fiddler working example
function updateSlider(btn) {
var $this = btn.closest(".item.with-sec-image");
var sliderContainer = $this.find('.images .slider'),
activeSlider = sliderContainer.children('.selected').removeClass('selected');
if (btn.hasClass('next')) {
(!activeSlider.is(':last-child')) ? activeSlider.next().addClass('selected'): sliderContainer.children('li').eq(0).addClass('selected');
} else {
(!activeSlider.is(':first-child')) ? activeSlider.prev().addClass('selected'): sliderContainer.children('li').last().addClass('selected');
}
}
// second image only on hover
$(function(){
$('.item.with-sec-image').on('mouseenter', function() {
var $this = $(this);
if (!$this.hasClass('images-initialized')) {
var url = $this.data('handle').replace('.html', '.ajax');
var purl = $this.data('handle');
$.getJSON(url, function(data) {
if (data.images.length > 1) {
var slider = $this.find('.slider');
if (data.images.length >= 2 && data.images.length != slider.find('li.selected').length) {
$.each(data.images, function(index, image) {
var img_url = image.replace('50x50x2', '400x400x2')
if (slider.find('li.selected').data('index') != index) {
var $newImage = $('<li><img src="' + img_url + '" /></li>')
slider.append($newImage);
}
});
}
}
}).done(function() {
$this.addClass('images-initialized');
});
}
}).on('click', '.slider-btn', function() {// this should be run outside the mouseenter function or else it will bind many times
updateSlider($(this))
});
});

How to display moving text field during other jQuery animation?

I am attempting to replicate the loading page at http://www.alessioatzeni.com/ but the percentage loaded text on my page will not display until the loading line animation completes. You can see my project page at https://jaredblumer.github.io/atzeniStudy/
If you inspect the HTML using Chrome Developer Tools, you'll see that the #loader-percentage span text is dynamically updating, but for a reason unbeknownst to me the text is not displaying until after the line animation ends.
The code I am currently using for this is as follows:
HTML
<div id="loader" class="loader">
<span id="loader-line" class="loader-line">
<span id="loader-percentage" class="loader-percentage"></span>
</span>
</div>
Javascript (loader.js)
$(document).ready(function() {
//Loading Page
var pageLoader = function() {
var $elements = $('body').find('img[src]');
$('body [style]').each(function(){
var src = $(this).css('background-image').replace(/^url\(["']?/, '').replace(/["']?\)$/, '');
if(src) {
$elements = $elements.add($('<img src="' + src + '"/>'));
}
});
var $loading = $('#loader');
var $loadPercentageLine = $('#loader-line');
var $loadPercentageText = $('#loader-percentage');
var elementsLoaded = 0;
var speed = 5000;
var animatePercentage = function(e) {
console.log(e);
$loadPercentageText.text(parseInt(e));
};
var loading = function() {
var percentage = 0;
if ($elements.length) {
percentage = parseInt((elementsLoaded / $elements.length) * 100);
}
$loadPercentageLine.stop().animate({
height:percentage + '%'
}, speed);
$loadPercentageText.stop().animate({
percentage:percentage
}, {
duration: speed,
step: animatePercentage
});
};
if($elements.length) {
loading();
$elements.each(function() {
elementsLoaded++;
loading();
});
}
};
pageLoader();
});
here is solution:
.loader-line{
overflow: visible !important;
}

app.receivedEvent is not a function

I am building a phonegap application and I get the following error message when debugging.
Uncaught TypeError: app.receivedEvent is not a function(…)** on line 18 of my JS code (I point it out below).
To be honest I have read many guides on the deviceready but I just can't figure out how to properly use it for my phonegap build code.
Here is my HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="format-detection" content="telephone=no" />
<meta name="msapplication-tap-highlight" content="no" />
<!-- Include meta tag to ensure proper rendering and touch zooming -->
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" href="css/index.css" />
<!-- Include jQuery Mobile stylesheets -->
<link rel="stylesheet" href="css/jquery.mobile-1.4.5.min.css">
<link href='https://fonts.googleapis.com/css?family=Lobster|Anton|Patua+One' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="css/fact_page.css">
<title>One Direction Facts</title>
</head>
<body>
<div data-role="page" id="pageone">
<div data-role="header">
<h1>One Direction - Fact of the Day</h1>
</div>
<div id="deviceready" data-role="main" class="ui-content">
<h2 id="todayh2" class="invisible"> Today's One Direction Fact:</h2>
<div id="quotebox" class="PulseEffect icon">
<div id="ShineDiv" class="shine"></div>
<div class="facebox fade icon">
<div id="ShineDiv2" class=""></div>
</div>
<p class="hidden" id="qotd"> Welcome to<br><strong>One Direction Facts.</strong><br><br>You will get a random fact each day.</p>
</div>
<a id="nextQ" class="" data-role="button" data-ajax="false">View Fact</a>
<div class="XPmeter animateXP" >
<span id="bar" style="width: 20%"></span>
<div id="medaldiv">
<img id="medal" src="images/medal3.svg"><p id="lvl">1</p>
</div>
</div>
</div>
<div data-role="footer">
<h1>New Features Coming Soon!</h1>
</div>
</div>
<!-- --------------------JS------------------------ -->
<script src="./js/jquery-1.11.3.min.js"></script>
<script src="./js/jquery.mobile-1.4.5.min.js"></script>
<script type="text/javascript" charset="utf-8" src="cordova.js"></script>
<script type="text/javascript" src="js/app_scripts.js"></script>
<script type="text/javascript" src="js/admob.js"></script>
<script type="text/javascript">
app.initialize();
</script>
</body>
</html>
Here is my JS:
var app = {
// Application Constructor
initialize: function() {
this.bindEvents();
},
// Bind Event Listeners
//
// Bind any events that are required on startup. Common events are:
// 'load', 'deviceready', 'offline', and 'online'.
bindEvents: function() {
document.addEventListener('deviceready', this.onDeviceReady, false);
},
// deviceready Event Handler
//
// The scope of 'this' is the event. In order to call the 'receivedEvent'
// function, we must explicitly call 'app.receivedEvent(...);'
onDeviceReady: function() {
/*--error is here-->*/ app.receivedEvent('deviceready');
},
// Update DOM on a Received Event
receivedEvent:
$("#nextQ").click(function(){
var tempd = new Date(); //Get today's date
//Checks if localstorage had 'DateOpened' already stored
// Note that by adding strings in there, we end up with a string instead of adding.
// Note the order: Year first, then month, then day.
// Also, since we display it, we put separators in and add 1 to month (since Jan = 0).
var str = tempd.getFullYear() + "-" + (tempd.getMonth() + 1) + "-" + tempd.getDate();
console.log("Today's date: " + str);
var localVal = localStorage.getItem('DateOpened');
console.log("Previous localVal: " + localVal);
if(localVal != null){
var difference = localVal.localeCompare(str);
}
console.log("localeCompare: " + difference);
//If stored date is older than this date do something:
if(localVal == null || difference < 0){
// If the localstorage doesn't exist, nothing happens
console.log("App will now run once for today.")
//Run the JS for the app (give new quote since it is a new day)
var Quotes = [];
var ID = [];
var Tag = [];
//Get quotes from JSON file
$.ajax({
url: './json/facts.json',
dataType: 'json',
type: 'get',
success: function(data){
console.log(data);
console.log("successfully imported the JSON file");
console.log(data.length); //Returns 64
totalQ = data.length;
for (i = 0; i < totalQ; i++){
ID[i] = data[i][0];
Tag[i] = data[i][1];
Quotes[i] = data[i][2];
}
console.log(Quotes.length);
}
})
.done(function(data){ //This waits for AJAX to be done before running
var Quote = new String;
var qnumber = 0;
var totalQ //The total number of available quotes to choose from
var CurrentImage = String;
totalQ = Quotes.length - 1;
console.log("TotalQ = " + totalQ);
//Get list of which facts have already been seen
var seen = JSON.parse(localStorage.getItem('seen'));
console.log("var seen = " + seen);
if (seen == null){
var seen = new Array(totalQ);
for (var i = 0; i < seen.length; ++i) {
seen[i] = false;
}
console.log("var seen = " + seen);
}
//Get a Quote
ChooseQuote(0,totalQ);
//Change the image depending on the quote
//replace the quote with a new one
$("#qotd:visible").hide();
$("#ShineDiv").addClass("shine");
$(".facebox").css("background-image",CurrentImage);
$(".facebox").css("opacity","1.0");
$("#qotd").html(Quote);
console.log("Image Changed");
increaseXP();
//================
function ChooseQuote(min,max){
//Choose 2 random numbers, one for quotes one for image
var RandomNum = Math.floor(Math.random()*(max-min+1)+min);
var ImageNum = Math.floor(Math.random()*(5-1+1)+1);
Quote = Quotes[RandomNum];
CurrentImage = "url(./images/FaceBoxes/" + Tag[RandomNum] + "/" + Tag[RandomNum] + ImageNum + ".png)";
if (seen[RandomNum] == true ) {
//Choose new quote
ChooseQuote(0,totalQ);
console.log("Has this fact been seen before? Answer: " + seen[RandomNum] );
var numOfTrue = 0;
for(var i=0; i<=totalQ; i++){
if(seen[i] === "true")
numOfTrue++;
}
if (numOfTrue = totalQ) {
localStorage.setItem('All_Facts_Seen:', true);
console.log("All the Facts have been seen. Resetting Facts.");
seen = new Array(totalQ); //Empty the seen Array
localStorage.setItem('seen', JSON.stringify(seen)); //Save the empty Array
}
}
else {
seen[RandomNum] = "true";
console.log("This fact has never been seen.")
}
console.log(Quote);
console.log(CurrentImage);
//Remeber which fact is displayed
localStorage.setItem('Curr_Fact', Quote);
localStorage.setItem('Curr_ImgUrl', CurrentImage);
localStorage.setItem('seen', JSON.stringify(seen));
}
//==================
//Save the current date in local storage
localStorage.setItem('DateOpened',str);
console.log("The App Ran, you can get a new fact tomorrow");
console.log("Current LocalStorage Date: " + str);
});
}
else {
//If it is still the same day, show the last fact & image
var Quote = localStorage.getItem('Curr_Fact');
var CurrentImage = localStorage.getItem('Curr_ImgUrl');
$("#qotd:visible").hide(); //Hide main quote
$("#ShineDiv2").addClass("shine");
if ($('h2').hasClass("invisible")){ //if heading is invisble show it, remove that class
$('h2').css('visibility','visible').hide().fadeIn('slow').removeClass("invisible");
}
$(".facebox").css("background-image",CurrentImage);
setTimeout( function() { //This is so that the first image and new image don't crossfade/stretch
$(".facebox").css("opacity","1.0");
}, 100);
$("#qotd").html(Quote); //Replace the main message with the actual quote
console.log("Showing the same fact as before. Wait until tomorrow to get a new fact.");
}
},
};
$(window).load(function() {
var headerh;
var footerh;
var pageh;
var hbtn_nextq;
headerh = $("div[data-role='header']").outerHeight();
footerh = $("div[data-role='footer']").outerHeight();
pageh = $(window).height();
console.log(headerh + " " + footerh + " " + pageh);
var difference = pageh - headerh - footerh;
$(".ui-content").css("height", difference);
var h1, h2, h3, h4 , h5;
h1 = $(".ui-content").outerHeight();
h2 = $(".ui-content>h2").outerHeight();
h3 = $("#quotebox").outerHeight(true);
h4 = $("#nextQ").outerHeight();
h5 = ((h1 - h2 - h3 - h4) /2) - 50;
console.log(h1);
console.log(h2);
console.log(h3);
console.log(h4);
console.log(h5);
var h5s = h5 + "px";
//$("#quotebox").css("margin-top",h5s);
$(".ui-content>h2").css("margin-top",h5s);
//$("#nextQ").css("margin-bottom",h5s);
//ShowXP();
//Make the quotebox flip over on click
$(".facebox, #ShineDiv").click(function(){
$("#quotebox").removeClass("PulseEffect")
$("#ShineDiv").removeClass("shine");
$(".facebox").css("opacity","0");
$("#qotd").fadeIn("slow", function(){});
});
ShowXP();
});
function increaseXP(){
//Get the lvl and xp from storage
var lvl = localStorage.getItem("lvl", lvl);
var XP = localStorage.getItem("XP", XP);
console.log("Old XP = " + XP + " Old Level = " + lvl);
lvl = parseInt(lvl);
XP = parseInt(XP);
//Increase XP
XP = XP + 25;
//Increase lvl
if (XP >= 100){
lvl = lvl + 1;
localStorage.setItem('XP',XP);
localStorage.setItem('lvl',lvl);
UpdateXP(XP);
setTimeout(function() {
ShowUP(lvl);
}, 200);
XP = XP - 100;
console.log("Current XP = " + XP + " Current Level = " + lvl);
UpdateXP(XP);
}
localStorage.setItem('XP',XP);
localStorage.setItem('lvl',lvl);
UpdateXP(XP);
}
function ShowXP(){
var XP = localStorage.getItem("XP");
var lvl = localStorage.getItem("lvl");
if (XP == null){
XP = 0;
localStorage.setItem("XP", XP);
}
if (lvl == null){
lvl = 1;
localStorage.setItem("lvl",lvl);
}
lvl = parseInt(lvl);
XP = parseInt(XP);
$("#lvl").text(lvl);
$(".XPmeter > span#bar").each(function() {
$(this)
.data("origWidth", XP)
.width(0)
.animate({
width: $(this).data("origWidth") + "%" // or + "%" if fluid
}, 1200);
});
}
function UpdateXP(XP){
$(".XPmeter > span#bar").each(function() {
$(this)
.animate({
width: XP + "%" // or + "%" if fluid
}, 1200);
});
}
function ShowUP(new_level){
$("#medal").animate({height: "100px" },600, function(){
$("#lvl").text(new_level);
$("#medal").animate({height: "50px" },600);
});
$(".XPmeter > span#bar").width("0");
}
//-------------------------------------------------------------//
// //
// This is the scirpt that will get the facts and display them //
// //
//-------------------------------------------------------------//
That's because your receivedEvent is not defined as a functions but as a property of the app object so it can't be called as a function.
You to change it from:
// Update DOM on a Received Event
receivedEvent:
to:
// Update DOM on a Received Event
receivedEvent: function(id) {

Javascript functions don't work after MVC Upgrade

I have upgraded a solution from MVC 3 to MVC 4.
I have 2 specific JavaScript functions that does not work anymore after upgrade.
Tabs
This is how the tabs now render
I suspect it has to do with the JavaScript version with the new framework? I am not sure.
Code:
<script type="text/javascript">
$(function () {
$("#tabs").tabs();
$('.taberize').each(function () {
var e = $(this);
var panels = e.parents('.ui-tabs-panel');
if (panels.length == 0) { return; }
var tabId = $(panels[0]).attr('id');
e.attr('href', e.attr('href') + '#' + tabId);
});
$(".container").each(function (e) {
var height = $(document).height() - 230;
$(this).height(height);
});
});
2. On Row Hover function
The On-Row-Hover function does not work anymore, I have a "Action Menu" on the left side of my WebGrid, and on row hover, it display functions like Edit and Details menu... this is done in JavaScript.
<script type="text/javascript">
var prevRow = null;
$('#gridData table tbody tr').not(':first').hover(function()
{
$('#myMenu').hide();
if (prevRow != this)
{
if (prevRow != null)
{
$(prevRow).css("background","");
$('.actionButtons', $(prevRow)).hide();
}
$(this).css("background","#EDEFFF");
$('.actionButtons', $(this)).show();
prevRow = this;
}
},
function()
{
if (!$('#myMenu').is(":visible"))
{
if (prevRow != null)
{
$(prevRow).css("background","");
$('.actionButtons', $(prevRow)).hide();
prevRow = null;
}
}
});
$(".openmenu").contextMenu({ menu: 'myMenu', leftButton: true },
function(action, el, pos) {
contextMenuWork(action, el.parents('tr')[0].id , pos);
});
function contextMenuWork(action, id) {
switch (action) {
case "insert":
{
if($.browser.msie&&$.browser.version.substr(0,1)<8){var url='#Url.Action("Create", "Account")';document.location=url}else{CreateNewAccount()}
break;
}
case "createtask":
{
var url = '#Url.Action("CreateFromAccount", "UserTask")' + '/' + id;
document.location = url;
break;
}
case "linkassessment":
{
var url = '#Url.Action("CreateFromAccount", "Questionnaire")' + '/' + id;
document.location = url;
break;
}
case "details":
{
var url = '#Url.Action("Details", "Account")' + '/' + id;
document.location = url;
break;
}
case "edit":
{
var url = '#Url.Action("Edit", "Account")' + '/' + id;
document.location = url;
break;
}
case "createperson":
{
if($.browser.msie&&$.browser.version.substr(0,1)<8){var url='#Url.Action("Create", "Person")';document.location=url}else{CreateNewPerson(id)}
break;
}
case "createopportunity":
{
var url = '#Url.Action("Create", "Opportunity")' + '/' + id;
document.location = url;
break;
}
}
}
});
</script>
<div id="gridData">
<ul id="myMenu" class="contextMenu" style="display: none">
<li class="insert">Create New</li>
<li class="detail">Details</li>
<li class="edit">Edit</li>
</ul>
</div>
<table>
<tr>
<th class="field-actions-account" style="width: 75px">
Actions
</th>
<tr id="#Html.Encode(item.AccountID)">
<td>
<div class="actionButtons" style="display:none">
<img src="#Html.Raw(#Url.Content("~/Content/img/document-pencil-icon.png"))" alt="Edit" title="Edit" style="border:none"/>
<img src="#Html.Raw(#Url.Content("~/Content/img/testDetailsIcon.gif"))" alt="Details" title="Details" style="border:none" />
<img src="#Html.Raw(#Url.Content("~/Content/img/options.gif"))" alt="More Options" class="openmenu" title="More Options"/>
</div>
put your javascript code in section like this:
#section Head
{
<script type="text/javascript">
$(function () {
$("#tabs").tabs();
$('.taberize').each(function () {
var e = $(this);
var panels = e.parents('.ui-tabs-panel');
if (panels.length == 0) { return; }
var tabId = $(panels[0]).attr('id');
e.attr('href', e.attr('href') + '#' + tabId);
});
$(".container").each(function (e) {
var height = $(document).height() - 230;
$(this).height(height);
});
});
</script>
}
then be sure your "#RenderSection("Head", false) is under your #Scripts.Render("~/bundles/jquery") in your layout like this :
#Scripts.Render("~/bundles/jquery")
#RenderSection("Head", false)
and finally check your BundleConfig class has a code like this file :
public static void RegisterBundles(BundleCollection bundles)
{
bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
"~/Scripts/jquery-{version}.js"));
}
The problem was, somehow the jquery.validate file has been modified, and that was causing my problem.

Categories

Resources