var backgroundImages = new Array(); // create an array holding the links of each image
backgroundImages[0] = "style/images/bg0.png";
backgroundImages[1] = "style/images/bg1.png";
backgroundImages[2] = "style/images/bg2.png";
backgroundImages[3] = "style/images/bg3.png";
backgroundImages[4] = "style/images/bg4.png";
backgroundImages[5] = "style/images/bg5.png";
backgroundImages[6] = "style/images/bg6.png";
var ImageCnt = 0;
function nextImage(direction) // this should take into account the current value (starts at 3) and determines whether a higher or lower value should be returned based on the direction
{
if(direction == "left")
{
ImageCnt-- ;
}
if(direction == "right")
{
ImageCnt++ ;
}
document.getElementById("body-1").style.background = 'url(' + backgroundImages[ImageCnt] + ')'; //put's the new background together for rendering by using the returned value from nextImage()
if(ImageCnt == 6)
{
ImageCnt = -1;
}
}
In this script, ImageCnt ++ is working fine, on the function "nextImage('right')" but on nextImage('left') which triggers ImageCnt-- , the function breaks. What am I doing wrong? (Newbie with js)
Well, your "wrap" code says to make it -1, but what if I then go left? It will try to access -2, which doesn't exist.
Try this instead:
ImageCnt = (ImageCnt + (direction == "left" ? backgroundImages.length-1 : 1)) % backgroundImages.length;
document.getElementById("body-1").style.background = "url('"+backgroundImages[ImageCnt]+"')";
Note also that it is very inefficient to build an array piece by piece like that. Try this:
var backgroundImages = [
"style/images/bg0.png",
"style/images/bg1.png",
"style/images/bg2.png",
"style/images/bg3.png",
"style/images/bg4.png",
"style/images/bg5.png",
"style/images/bg6.png",
];
Related
So I am creating a game where a spaceship moves and it must avoid a fireball image in order to win. My issue is that I have only one fireball looping over and over. Instead, I would like to have many fireballs, which are multiplied as time passes. I think I should need to incorporate an array and use push() method but I tried and it didn't worked. If anyone could help me, it would be very appreciated. Thanks
//Fireball script
function fireballScript(offset) {
return Math.floor(Math.random() * (window.innerWidth - offset))
}
let fireballMovement = {
x: fireballScript(fireball.offsetWidth),
y: 0
}
const fireLoop = function () {
fireballMovement.y += 1
fireball.style.top = fireballMovement.y + 'px'
if (fireballMovement.y > window.innerHeight) {
fireballMovement.x = fireballScript(fireball.offsetWidth)
fireball.style.left = fireballMovement.x + 'px'
fireballMovement.y = 0
fireball.setAttribute('hit', false)
}
}
fireball.style.left = fireballMovement.x + 'px'
let fireballSpeed = setInterval(fireLoop, 1000 / 250)
let fireball = document.querySelector("#fireball")
<img src = "Photo/fireball.png" id = "fireball" >
//Stop game on collision
function checkCollision() {
if (detectOverlap(spaceship, fireball) && fireball.getAttribute('hit') == 'false') {
hits++
fireball.setAttribute('hit', true)
alert("lost")
}
setTimeout(checkCollision, 1)
}
var detectOverlap = (function () {
function getPositions(spaceship) {
var pos = spaceship.getBoundingClientRect()
return [[pos.left, pos.right], [pos.top, pos.bottom]]
}
function comparePositions(p1, p2) {
let r1 = p1[0] < p2[0] ? p1 : p2
let r2 = p1[0] < p2[0] ? p2 : p1
return r1[1] > r2[0] || r1[0] === r2[0]
}
return function (a, b) {
var pos1 = getPositions(a),
pos2 = getPositions(b)
return comparePositions(pos1[0], pos2[0]) && comparePositions(pos1[1], pos2[1])
}
})()
let spaceship = document.querySelector("#icon")
<img src = "Photo/Spaceship1.png" id="icon">
Ps: I asked this question a dozen of times but I could never get an answer which is incorporate into my code. It would be very helpful if someone could fix this... thanks again
You need to have an array of fireballs
var fireballs = [];
Make a constructor for fireballs instead of putting them directly in the html
function fireball(x, y) {
movementX = x;
movementY = y;
}
Then push new ones into the array with dynamic position values. To add them to the document, you need to append them to a parent element. If the <body> is that parent, you'd do this:
let f = new fireball(10, 20)
fireballs.push(f)
document.body.appendChild(f)
In your update, iterate through the fireballs and update their movement.
fireballs.forEach((fireball) => {
// update position for each fireball
});
My mission is to tweak this website https://www.mintpal.com/market/XC/BTC# so it will show a different color for the value if it sees "buy orders" over 2.00000000 BTC.
As an example, you check the image http://i.imgur.com/hZBGiTu.png ( the example worked because i targeted them each one separately with "#buyTotal-0-00126011" and so on.
I only want that td#buyTotal pane to be changed.
I tried to target it with the following:
1 - var cell = $('td') - it works, but it changes the values globally
2 - var cell = $('#buyTotal' + price + value.total) - not working
3 - var cell = $('td#buyTotal') - not working.
The code should look similar to this in the end...
var cell = $('td#buyTotal')
cell.each(function() {
var cell_value = $(this).html();
if ((cell_value >= 0) && (cell_value >=2.00000000)) {
$(this).css({'background' : '#FF0000'});
} else if ((cell_value >= 3) && (cell_value >=5.00000000)) {
$(this).css({'background' : '#FF0000'});
} else if (cell_value >= 8.00000000) {
$(this).css({'background' : '#FF0000'});
}
});
You can also access this as a shortcut ' mintpal.com/assets/js/market.js '
If i omitted something, please let me know. Thanks....
Edit: I'm only playing with the code inspector/console on the website. What i want is extremely simple. It's just that i cannot target the id. I updated the photo also.
This will require regex.
var cells = document.querySelectorAll('*[id^="buyTotal"]');
for(var i = 0; i < cells.length; i++) {
if(cells[i].innerHTML > 2) { cells[i].style.backgroundColor = 'red'; }
}
I'm writing a script which changes the colours of a stick-man's arms and legs. Once "he" is selected, it effectively just mirrors the colours:
//Declare and initialize variables
var msgType = "";
var app;
var docRef = app.activeDocument;
var testColor = docRef.swatches.getByName("CMYK Green");
var leftColor = docRef.swatches.getByName("LeftColor");
var rightColor = docRef.swatches.getByName("RightColor");
function sameColor(CMYKColor1, CMYKColor2) {
"use strict";
var isTheSameColor;
if ((CMYKColor1.cyan === CMYKColor2.cyan) && (CMYKColor1.magenta === CMYKColor2.magenta) && (CMYKColor1.yellow === CMYKColor2.yellow) && (CMYKColor1.black === CMYKColor2.black)) {
isTheSameColor = true;
} else {
isTheSameColor = false;
}
return isTheSameColor;
}
// check if a document is open in Illustrator.
if (app.documents.length > 0) {
var mySelection = app.activeDocument.selection;
var index;
// Loop through all selected objects
for (index = 0; index < mySelection.length; index += 1) {
// Switch left and right colours
if (sameColor(mySelection[index].strokeColor, leftColor.color)) {
mySelection[index].strokeColor = rightColor.color;
}
if (sameColor(mySelection[index].strokeColor, rightColor.color)) {
mySelection[index].strokeColor = leftColor.color;
}
if (sameColor(mySelection[index].fillColor, leftColor.color)) {
mySelection[index].fillColor = rightColor.color;
}
if (sameColor(mySelection[index].fillColor, rightColor.color)) {
mySelection[index].fillColor = leftColor.color;
}
}
}
It works, but it only works once (i.e. I can't toggle the change again). If I undo the change and try again it works again. Why is this?
After a lot of head-scratching / debugging it turns out that it was changing the CMYK values to be not quite the same (by a tiny fraction).
Changed the following:
if ((CMYKColor1.cyan === CMYKColor2.cyan) ...
to:
if ((Math.round(CMYKColor1.cyan) === Math.round(CMYKColor2.cyan)) ...
and it works fine now.
I am a newbie and I have inherited some nasty jquery code. I am trying to find a way so that if an error is found then it replaces the string with another string. This is the original code..
W.load = function (b) {
var c, d, g = W.prep; S = ! 0, Q = ! 1, O = x[P], b || _(a.extend(J, a.data(O, e))), ba(l), ba(h, J.onLoad), J.h = J.height? Z(J.height, "y") - M - K: J.innerHeight && Z(J.innerHeight, "y"), J.w = J.width? Z(J.width, "x") - N - L: J.innerWidth && Z(J.innerWidth, "x"), J.mw = J.w, J.mh = J.h, J.maxWidth &&(J.mw = Z(J.maxWidth, "x") - N - L, J.mw = J.w && J.w < J.mw? J.w: J.mw), J.maxHeight &&(J.mh = Z(J.maxHeight, "y") - M - K, J.mh = J.h && J.h < J.mh? J.h: J.mh), c = J.href, V = setTimeout(function () {
B.show()
},
100), J.inline?(Y().hide().insertBefore(a(c)[0]).one(l, function () {
a(this).replaceWith(z.children())
}), g(a(c))): J.iframe? g(" "): J.html? g(J.html): $(c)?(a(Q = new Image).addClass(f + "Photo").error(function () {
//J.title = ! 1, g(Y("Error").text("This image could not be loaded"))
J.title = ! 1, a(this).href.replace('http://www.old.com','http://www.new.com');
}).load(function () {
var a; Q.onload = null, J.scalePhotos &&(d = function () {
Q.height -= Q.height * a, Q.width -= Q.width * a
},
J.mw && Q.width > J.mw &&(a =(Q.width - J.mw) / Q.width, d()), J.mh && Q.height > J.mh &&(a =(Q.height - J.mh) / Q.height, d())), J.h &&(Q.style.marginTop = Math.max(J.h - Q.height, 0) / 2 + "px"), x[1] &&(P < x.length - 1 || J.loop) &&(Q.style.cursor = "pointer", Q.onclick = function () {
W.next()
}), m &&(Q.style.msInterpolationMode = "bicubic"), setTimeout(function () {
g(Q)
},
I have changed the code to this..
J.title = ! 1, a(this).href.replace('http://www.old.com','http://www.new.com');
But its not working. Ggr! Any help would be greatly appriciated. :)
UPDATE*
The code above is the complete code for the section I am working in..
UPDATE #2
This answer works but I need to do...
a(this).attr('src', function(i, current){
if ( i === 'http://www.old.com'){
return current.replace('http://www.old.com','http://www.new.com');
}
else if ( i === 'http://www.older.com'){
return current.replace('http://www.older.com','http://www.new.com');
}
else ();
})
This isn't working!! Help!!
Try
this.href.replace('http://old.com/' , 'http://new.com/');
If you want to change the actual attribute to a new one on the current element then
this.href = this.href.replace('http://old.com/' , 'http://new.com/');
If you are inside a handler that refers to an <a> element then this refers to that object and you do not need to make a jquery object out of it, to access its properties.. so this.href will refer directly to the href property of the link.
Disclaimer: That is obfusated/encoded script and you should better find the original from which this was produced.. This code makes no sense and our suggestion are really in the blind..
From a first look it seems the this is an image and not a link, so if you want to show a new image then you would need to change the src attribute and not the href which does not exist on images..
a(this).attr('src', function(i, current){ return current.replace('http://www.old.com','http://www.new.com');})
But you should also do a console.log(a.fn.jquery) in there to make sure that a is a reference to jQuery
Do you need to do a replace ? If you just want to change the url then you can just do.
J.title = ! 1, $(this).attr('href', 'http://new.com/*');
Which will replace the current url to the new url given.
I am trying to make images that move around the screen that do something when they are clicked. I am using setInterval to call a function to move the images. Each image has the onclick attribute set. The problem is that the clicks are not registering.
If I take out the setInterval and just keep the images still, then the clicks do register.
My code is here (html, css, JavaScript): https://jsfiddle.net/contini/nLc404x7/4/
The JavaScript is copied here:
var smiley_screen_params = {
smiley_size : 100, // needs to agree with width/height from css file
num_smilies: 20
}
var smiley = {
top_position : 0,
left_position : 0,
jump_speed : 2,
h_direction : 1,
v_direction : 1,
intvl_speed : 10, // advance smiley every x milliseconds
id : "smiley"
}
function randomise_direction(s) {
var hd = parseInt(Math.random()*2);
var vd = parseInt(Math.random()*2);
if (hd === 0)
s.h_direction = -1;
if (vd === 0)
s.v_direction = -1;
}
function plotSmiley(sp /* sp = smiley params */) {
var existing_smiley = document.getElementById(sp.id);
if (existing_smiley !== null)
// delete existing smiley so we can move it
document.getElementById("smileybox").removeChild(existing_smiley);
var smiley_to_plot = document.createElement('img');
smiley_to_plot.setAttribute('src', "http://i.imgur.com/C0BiXJx.png");
smiley_to_plot.setAttribute('id', sp.id);
smiley_to_plot.setAttribute('onclick', "my_click_count()");
smiley_to_plot.style.position = 'absolute';
smiley_to_plot.style.top = sp.top_position + "px";
smiley_to_plot.style.left = sp.left_position + "px";
document.getElementById("smileybox").appendChild(smiley_to_plot);
}
function random_direction_change() {
var r = parseInt(Math.random()*200);
if (r===0)
return true;
else
return false;
}
function moveFace(sp_array /* sp_array = smiley params array */) {
var i;
var sp;
for (i=0; i < sp_array.length; ++i) {
// move ith element
sp = sp_array[i];
if (
(sp.h_direction > 0 && sp.left_position >= smiley_screen_params.width - smiley_screen_params.smiley_size) ||
(sp.h_direction < 0 && sp.left_position <= 0) ||
(random_direction_change())
) {
sp.h_direction = -sp.h_direction; // hit left/right, bounce off (or random direction change)
}
if (
(sp.v_direction > 0 && sp.top_position >= smiley_screen_params.height - smiley_screen_params.smiley_size) ||
(sp.v_direction < 0 && sp.top_position <= 0) ||
(random_direction_change())
) {
sp.v_direction = -sp.v_direction; // hit top/bottom, bounce off (or random direction change)
}
sp.top_position += sp.v_direction * sp.jump_speed;
sp.left_position += sp.h_direction * sp.jump_speed;
plotSmiley(sp);
}
}
if (typeof Object.create !== 'function') {
Object.create = function(o) {
var F = function () {};
F.prototype = o;
return new F();
};
}
function generateFaces() {
var smilies = new Array();
var s;
var i;
var css_smileybox=document.getElementById("smileybox");
var sb_style = getComputedStyle(css_smileybox, null);
// add info to the screen params
smiley_screen_params.width = parseInt(sb_style.width);
smiley_screen_params.height = parseInt(sb_style.height);
// create the smileys
for (i=0; i < smiley_screen_params.num_smilies; ++i) {
s = Object.create(smiley);
s.id = "smiley" + i;
s.top_position = parseInt(Math.random() * (smiley_screen_params.height - smiley_screen_params.smiley_size)),
s.left_position = parseInt(Math.random() * (smiley_screen_params.width - smiley_screen_params.smiley_size)),
randomise_direction(s);
smilies.push(s);
}
setInterval( function(){ moveFace(smilies) }, smiley.intvl_speed );
}
var click_count=0;
function my_click_count() {
++click_count;
document.getElementById("mg").innerHTML = "Number of clicks: " + click_count;
}
generateFaces();
The generateFaces() will generate parameters (for example, coordinates of where they are placed) for a bunch of smiley face images. The setInterval is within this function, and calls the moveFace function to make the smiley faces move at a fixed interval of time. moveFace computes the new coordinates of each smiley face image and then calls plotSmiley to plot each one on the screen in its new location (removing it from the old location). The plotSmiley sets the onclick attribute of each image to call a dummy function just to see if the clicks are registering.
Thanks in advance.
This is not a complete answer but it could give you some perspective to improve your code.
First of all, your idea of deleting the existing img so wrong. If it does exist, all you need is to just change its position so instead of this
if (existing_smiley !== null)
// delete existing smiley so we can move it
document.getElementById("smileybox").removeChild(existing_smiley);
you should do something like this:
if (existing_smiley !== null)
var smiley_to_plot = existing_smiley;
else {
var smiley_to_plot = document.createElement('img');
smiley_to_plot.setAttribute('src', "http://i.imgur.com/C0BiXJx.png");
smiley_to_plot.setAttribute('id', sp.id);
smiley_to_plot.style.position = 'absolute';
document.getElementById("smileybox").appendChild(smiley_to_plot);
smiley_to_plot.addEventListener('click', my_click_count);
}
smiley_to_plot.style.top = sp.top_position + "px";
smiley_to_plot.style.left = sp.left_position + "px";
As you can see new image is only being added if it's not already there. Also notice that adding events by using .setAttribute('onclick', "my_click_count()"); is not a good way to do. You should use .addEventListener('click', my_click_count); like I did.
Like I said this is not a complete answer but at least this way they response to the click events now.
FIDDLE UPDATE
Good luck!