IE8-specific JavaScript error? - javascript

I have a problem in IE8:
function costructor(sectionId){
$('#nextG').ready(function(){
var counterBis = 0;
slider = '.slider0'+sectionId;
//sliderBox = $(slider).closest('.floatContent');
unitScrollBis = $(slider).find('.floatImg').eq(0).width();
maxImg = $(slider).find('.floatImg').length-2;
/*problem*/
prev = "#" + $("#controller0" + sectionId).find(".controller").eq(0).attr("id");
next = "#" + $("#controller0" + sectionId).find(".controller").eq(0).attr("id");
/*END*/
console.log(prev);
console.log(next);
makeMove(counterBis,unitScrollBis,prev,next,slider,maxImg);
function makeMove(counterBis,unitScrollBis,prev,next,slider,maxImg){
if(counterBis <= 0){
$(prev).fadeOut("fast");
}
else if(counterBis >= maxImg){
$(next).fadeOut("fast");
}
$(next).click(function(){
if(counterBis <= maxImg){
counterBis++;
$(prev).fadeIn("fast");
slide(counterBis);
}
else{
$(next).fadeOut("fast");
}
});
$(prev).click(function(){
if(counterBis > 0){
counterBis--;
$(next).fadeIn("fast");
slide(counterBis);
}
else{
$(prev).fadeOut("fast");
}
});
function slide(counterBis){
$(slider).animate({
marginLeft: '-' + (unitScrollBis*counterBis) + 'px'
},1000);
};
};
IE8 says that: SCRIPT438: Object doesn't support property or method Can anyone help me?
The problem is only in IE8, I don't understand why IE can't build this string.
thanks for the help

You need to declare variables with the var keyword, otherwise older versions of IE will not recognise them and possibly break.
So change
prev = "#" + $("#controller0" + sectionId).find(".controller").eq(0).attr("id");
next = "#" + $("#controller0" + sectionId).find(".controller").eq(0).attr("id");
to
var prev = "#" + $("#controller0" + sectionId).find(".controller").eq(0).attr("id");
var next = "#" + $("#controller0" + sectionId).find(".controller").eq(0).attr("id");
and everything should work as it does in other browsers/IE9

Related

Play a sequence of images with JS, using $timeout to schedule frames

I'm using AngularJS to prefetch images in cache client and then I want to animate those prefetched images.
My code for the prefetching:
$scope.prefetch=function(limit) {
for (var i=0; i<limit; i++) {
var date = new Date($scope.dt);
if ($scope.fileFlag == false) {
if ($scope.viewmodel.timeResolution == 'yearly')
date = new Date(date.setFullYear(date.getFullYear() + i));
else if ($scope.viewmodel.timeResolution == 'monthly')
date = new Date(date.setMonth(date.getMonth() + i));
else if ($scope.viewmodel.timeResolution == 'daily') {
date = new Date(date.setDate(date.getDate() + i));
}
} else {
date = $scope.files[$scope.files.indexOf($scope.idSelectedVote) + i];
}
console.log( $http.get(site_url + "mwf/" + $scope.viewmodel.dataSet + "/" + $scope.viewmodel.varName + "/" + $scope.viewmodel.region + "/" + date + "/map/?vMin=" + $scope.VMin + "&vMax=" + $scope.VMax + "&type=" + $scope.viewmodel.type + "&cmap=" + $scope.viewmodel.colorMap, {'cache': true}));
}
};
then i do something like this to play those images
$scope.play=function(limit) {
for (var i=0; i<limit; i++) {
$scope.map.src= site_url + "mwf/" + $scope.viewmodel.dataSet + "/" + $scope.viewmodel.varName + "/" + $scope.viewmodel.region + "/" + parseInt(date)+i + "/map/?vMin=" + $scope.VMin + "&vMax=" + $scope.VMax + "&type=" + $scope.viewmodel.type + "&cmap=" + $scope.viewmodel.colorMap;
$scope.sleepFor(500);
}
};
$scope.sleepFor = function( sleepDuration ) {
var now = new Date().getTime();
while(new Date().getTime() < now + sleepDuration){ /* do nothing */ }
}
My problem is when I call play(4) it displays only the first and the last images and not an animation. Any idea on how can I improve this code or a different approach so I can do this?
Your sleepFor is an idle loop: you spin and do nothing, but you prevent any other work from being done. This is not the way in Javascript to delay work for a set period of time, or schedule a function to be run at a later time. In Javascript we use window.setTimeout -- and in Angular we have the convenient $timeout service to provide that:
$scope.play = function(limit) {
for (var i=0; i < limit; i++) {
$scope.map.src = site_url + "mwf/" + $scope.viewmodel.dataSet + "/" + $scope.viewmodel.varName + "/" + $scope.viewmodel.region + "/" + parseInt(date)+i + "/map/?vMin=" + $scope.VMin + "&vMax=" + $scope.VMax + "&type=" + $scope.viewmodel.type + "&cmap=" + $scope.viewmodel.colorMap;
var nextFrameMs = 500;
$timeout($scope.play, nextFrameMs);
}
};
In your example, wherever your $scope is provided to you -- assuming this is in a controller, you will have some line like module.controller($scope, ...) -- you will have to inject the $timeout service to be able to use it.
Additional resources:
Angular's documentation on $timeout
MDN documentation of window.setTimeout
You have to use intervals otherwise your code will block the execution of other code
Using Angular's built in $interval service is the solution:
var playInterval;
$scope.play = function(limit) {
var interval = 1000 / 20; //20 frames per second
var i = 0;
$interval.cancel(playInterval); //stop previous animations if any
if(i < limit) {
$scope.map.src = getSrc(i++);
var cache = $interval(function() {
if(i >= limit) {
return $interval.cancel(playInterval); //or you can replace with `i = 0;` to loop the animation
}
$scope.map.src = getSrc(i++);
}, interval);
}
};
function getSrc(i) {
return site_url + "mwf/" + $scope.viewmodel.dataSet + "/" + $scope.viewmodel.varName + "/" + $scope.viewmodel.region + "/" + parseInt(date)+i + "/map/?vMin=" + $scope.VMin + "&vMax=" + $scope.VMax + "&type=" + $scope.viewmodel.type + "&cmap=" + $scope.viewmodel.colorMap;
}

JQuery background URL uncaught syntax error

I'm trying to make a background slideshow using jQuery. I'm trying to have a hidden div (nextDiv) on the right of activeDiv slide nextDiv over activeDiv so that activeDiv will be overlapped by nextDiv. Once that is done, the background of nextDiv will then be changed to prepare for the new background image. Below is the code I have written.
// Scroll background
var bgClicked = false;
var bgList = [];
$(".bg-img").each(function(idx, el) {
bgList.push($(el).css('background-image').substr(4, 50));
bgList[idx] = bgList[idx].substr(0, bgList[idx].length -1);
});
var bgNum = bgList.length;
var bgNextDiv = $("#bg-next");
var bgActiveDiv = $("#bg-active");
var bgActive = 0;
var bgNext = 1;
// Scroll until clicked
console.log(bgList);
if(bgClicked == false) {
setInterval(function() {
$(bgList[bgNext]).animate({left:0}, 1000, 'linear', function() {
bgActiveDiv.css('background-image', 'url(' + bgList[bgNext] + ')');
bgActive = bgNext;
bgNext = bgNext < bgNum - 1 ? bgNext + 1 : 0;
bgNextDiv.css('background-image', 'url(' + bgList[bgNext] + ')');
});
}, 5000);
}
However, I'm getting
Uncaught Error: Syntax error, unrecognized expression: http://localhost:3000/img/bg2_2560x1440px.jpg`
when setting
bgActiveDiv.css('background-image', 'url(' + bgList[bgNext] + ')');
I think I missed something, but I don't know where.
Please help?
Cheers,
Agi
EDIT 1
Content of bgList = ["http://localhost:3000/img/bg1_2560x1440px.jpg", "http://localhost:3000/img/bg2_2560x1440px.jpg"]
You are using bgList[bgNext] as jQuery selector that is why you are getting error.
So, use this instead:
$(".bg-img:eq(" + bgNext + ")").animate({left:0}, 1000, 'linear', function() {
bgActiveDiv.css('background-image', 'url(' + bgList[bgNext] + ')');
bgActive = bgNext;
bgNext = bgNext < bgNum - 1 ? bgNext + 1 : 0;
bgNextDiv.css('background-image', 'url(' + bgList[bgNext] + ')');
});

Why is line break being written as a string?

I am trying to write a program that submits text on my website and I am having a lot of trouble trying to do a line break after the text because break line is being written as a string.
var main = function() {
var today = new Date();
var month = parseInt(today.getMonth() + 1);
var day = parseInt(today.getDate());
var year = parseInt(today.getFullYear());
$(".btn").click(function() {
var post = $(".status-box").val();
$("<li>").text(post + "<br>" + month + "/" + day + "/" + year).prependTo(".posts");
$(".status-box").val("");
$(".counter").text("140");
$(".btn").addClass("disabled");
});
$(".status-box").keyup(function() {
var postlength = $(this).val().length;
var charactersLeft = 140 - postlength;
$(".counter").text(charactersLeft);
if (charactersLeft < 0) {
$(".btn").addClass("disabled");
} else if (charactersLeft === 140) {
$(".btn").addClass("disabled");
} else {
$(".btn").removeClass("disabled");
}
});
$(".btn").addClass("disabled");
};
$(document).ready(main);
You are using .text() which will ALWAYS html-encode the text provided...use .html() instead
$("<li>").html(post + "<br>" + month + "/" + day + "/" + year).prependTo(".posts");

"error CS1012: Too many characters in character literal"

i have a JavaScript code of photo gallery with a slider but there's a problem :
var partnum = "<%Response.Write(Request.QueryString["partno"]); %>";
// check if the file is exiset -- it's running in bar() function -- run on servers and local host.
function UrlExists(url) {
var http = new XMLHttpRequest();
http.open('GET', url, false);
http.send();
return http.status != 404;
}
// push images paths to array
function bar() {
var exict = 0;
var counter = 0; //counter of array's index
for (var i = 1 ; exict < 30; i++) {
// if there isn't .jpg or .gif
if (!UrlExists("/assets/catalog/parts/" + partnum + "_" + i + ".jpg") && !UrlExists("/assets/catalog/parts/" + partnum + "_" + i + ".gif")) {
exict = exict + 1;
}
// if there is .jpg
if (UrlExists("/assets/catalog/parts/" + partnum + "_" + i + ".jpg") && !UrlExists("/assets/catalog/parts/" + partnum + "_" + i + ".gif")) {
arrOfImgs.push("/assets/catalog/parts/" + partnum + "_" + i + ".jpg");
counter = counter + 1;
}
// if there is .gif
if (UrlExists("/assets/catalog/parts/" + partnum + "_" + i + ".gif") && !UrlExists("/assets/catalog/parts/" + partnum + "_" + i + ".jpg")) {
arrOfImgs.push("/assets/catalog/parts/" + partnum + "_" + i + ".gif");
gifIndex.push(i);
counter = counter + 1;
}
}
}
but it was not work, so i tried to change var partnum
var partnum = <%= new JavaScriptSerializer().Serialize(Request.QueryString['partno']) %>;
but I got error: "error CS1012: Too many characters in character literal". I'm still not sure that this is the issue, as my original code does work (you can see the initial product image loaded when you visit the site .baumhaus and click on a product range and then any product, you will see the action - before it disappears once it tries to render the thumbnails).
How about
var partnum = '<%= Request.QueryString["partno"] %>'";

using touchstart causes screen to become fuzzy on touchstart

I am currently testing touchstart functionality on my device (Samsung galaxy S2) for my game. I am programming using javascript and jquery wrapped under phonegap in android and currently having issues as follows:
my touch start event (e.g triggering an attack button "touchstart" event to run some javascript to perform the attack action) causes my screen to become temporarily fuzzy, then back to normal in less than a second, so more like a screen flicker where images become jittery). I am not using css transforms or transitions just plain css and images.
Can someone please let me know if they have encountered moreorless similar issues to mine. A bit at a loss whether it is a hardware or touchstart issue where i can solve that problem.
Sample Javascript below for my navigation controls (left, up, down, right touchstart tap):
if ('ontouchstart' in document.documentElement) {
var left = document.getElementById('left');
left.addEventListener("touchstart", function(e){
if(controlsPlayerChar == '')
{
return false;
}
var l_oldCell = $('#' + controlsPlayerChar).parent().attr('id');
var l_xy = l_oldCell.split('_');
var l_x = l_xy[0];
var l_y = l_xy[1];
if(l_y == 1)
{
direction = "left";
setCharDynamics(controlsPlayerChar);
return false;
}
var l_newCell = l_x + '_' + (parseInt(l_y) - 1);
// validate if next cell is empty
if($('#' + l_newCell + ':has(".shadow")').val() != undefined
|| $('#' + l_newCell + ':has(".ally")').val() != undefined
|| $('#' + l_newCell + ':has(".obstacle")').val() != undefined)
{
direction = "left";
setCharDynamics(controlsPlayerChar);
return false;
}
$('#' + l_newCell).append($('#' + controlsPlayerChar));
$('#' + l_oldCell + ' ' + '#' + controlsPlayerChar).remove();
// set char direction to 'left' and set next footstep
setDirection('left');
setFootstep(footstep);
setCharDynamics(controlsPlayerChar);
});
var up = document.getElementById('up');
up.addEventListener("touchstart", function(e){
if(controlsPlayerChar == '')
{
return false;
}
var u_oldCell = $('#' + controlsPlayerChar).parent().attr('id');
var u_xy = u_oldCell.split('_');
var u_x = u_xy[0];
var u_y = u_xy[1];
if(u_x == 1)
{
direction = "up";
setCharDynamics(controlsPlayerChar);
return false;
}
var u_newCell = (parseInt(u_x) - 1) + '_' + u_y;
// validate if next cell is empty
if($('#' + u_newCell + ':has(".shadow")').val() != undefined
|| $('#' + u_newCell + ':has(".ally")').val() != undefined
|| $('#' + u_newCell + ':has(".obstacle")').val() != undefined)
{
direction = "up";
setCharDynamics(controlsPlayerChar);
return false;
}
$('#' + u_newCell).append($('#' + controlsPlayerChar));
$('#' + u_oldCell + ' ' + '#' + controlsPlayerChar).remove();
// set char direction to 'up' and set next footstep
setDirection('up');
setFootstep(footstep);
setCharDynamics(controlsPlayerChar);
});
var down = document.getElementById('down');
down.addEventListener("touchstart", function(e){
if(controlsPlayerChar == '')
{
return false;
}
var d_oldCell = $('#' + controlsPlayerChar).parent().attr('id');
var d_xy = d_oldCell.split('_');
var d_x = d_xy[0];
var d_y = d_xy[1];
if(d_x == rows)
{
direction = "down";
setCharDynamics(controlsPlayerChar);
return false;
}
var d_newCell = (parseInt(d_x) + 1) + '_' + d_y;
// validate if next cell is empty
if($('#' + d_newCell + ':has(".shadow")').val() != undefined
|| $('#' + d_newCell + ':has(".ally")').val() != undefined
|| $('#' + d_newCell + ':has(".obstacle")').val() != undefined)
{
direction = "down";
setCharDynamics(controlsPlayerChar);
return false;
}
$('#' + d_newCell).append($('#' + controlsPlayerChar));
$('#' + d_oldCell + ' ' + '#' + controlsPlayerChar).remove();
// set char direction to 'down' and set next footstep
setDirection('down');
setFootstep(footstep);
setCharDynamics(controlsPlayerChar);
});
var right = document.getElementById('right');
right.addEventListener("touchstart", function(e){
if(controlsPlayerChar == '')
{
return false;
}
var r_oldCell = $('#' + controlsPlayerChar).parent().attr('id');
var r_xy = r_oldCell.split('_');
var r_x = r_xy[0];
var r_y = r_xy[1];
if(r_y == cols)
{
direction = "right";
setCharDynamics(controlsPlayerChar);
return false;
}
var r_newCell = r_x + '_' + (parseInt(r_y) + 1);
// validate if next cell is empty
if($('#' + r_newCell + ':has(".shadow")').val() != undefined
|| $('#' + r_newCell + ':has(".ally")').val() != undefined
|| $('#' + r_newCell + ':has(".obstacle")').val() != undefined)
{
direction = "right";
setCharDynamics(controlsPlayerChar);
return false;
}
$('#' + r_newCell).append($('#' + controlsPlayerChar));
$('#' + r_oldCell + ' ' + '#' + controlsPlayerChar).remove();
// set char direction to 'right' and set next footstep
setDirection('right');
setFootstep(footstep);
setCharDynamics(controlsPlayerChar);
});
}
Please let me know if you think anything is amiss with regards to above script. The way I add the touchstart event is the same in other areas of my script when e.g to launch an attack or launch an options menu for instance.
Seems that this is tap highlighting.
You can try to disable this effect applying -webkit-tap-highlight-color CSS property on your controls or disable this in all elements using * selector.
For example:
.someelement {
-webkit-tap-highlight-color: transparent;
}
We've ran into this issue when using translate3d transformations.
We fixed it by setting
* { -webkit-transform: translate3d(0,0,0,); }
so that every element is initialized for the 3d space
First of all, make sure you are calling preventDefault() on the event. I've noticed that if you are targeting mouse events as well, they can fire on touch. Otherwise, I use a slightly different method of disabling touch highlighting. Try:
-webkit-tap-highlight-color: rgba(0,0,0,0);
In the css for your button.

Categories

Resources