So I watched a tutorial on YouTube showing me how to make a simple version of the dino-game using JavaScript. I followed that tutorial and afterwards, I decided to add some changes to the code. After changing a few aspects, this is what I have:
// Start check
setTimeout(function startobstacles() {
obstacle.classList.add("animateObstacle")
}, 3000);
// Variable definition
var character = document.getElementById('character');
var obstacle = document.getElementById('obstacle');
var score = 0
var dead = false
// Jump movement
function jump() {
character.classList.add("animateJump");
setTimeout(function() {
character.classList.remove("animateJump");
}, 500);
}
// Check if player lost
var checkDead = setInterval(function() {
var characterTop = parseInt(window.getComputedStyle(character).getPropertyValue("top"));
var obstacleLeft = parseInt(window.getComputedStyle(obstacle).getPropertyValue("left"));
if (obstacleLeft < 20 && obstacleLeft > 0 && characterTop >= 130) {
obstacle.style.animation = "none";
obstacle.style.diaplay = "none";
dead = true
var check = alert("You lost! Your score was " + score + ".");
if (typeof check == 'undefined') {
location.reload();
}
}
}, 10);
// Scoring system
setInterval(function() {
if (dead == false) {
score += 1;
highScore = window.localStorage.getItem('high_score');
if (score > highScore || highScore == null) {
window.localStorage.setItem('high_score', score);
}
highScore = parseInt(window.localStorage.getItem('high_score'));
document.getElementById("scoreBoard").innerHTML = "Your score: " + score + " | Your personal best: " + highScore;
}
}, 2000)
* {
padding: 0;
margin: 0;
}
.noselect {
-webkit-touch-callout: none; /* iOS Safari */
-webkit-user-select: none; /* Safari */
-khtml-user-select: none; /* Konqueror HTML */
-moz-user-select: none; /* Firefox */
-ms-user-select: none; /* Internet Explorer/Edge */
user-select: none; /* Non-prefixed version, currently
supported by Chrome and Opera */
}
#scoreBoard{
font-family: cursive;
font-size: 16px;
}
#game {
width: 500px;
height: 200px;
border: 1px solid black;
background-image: url("images/background.png");
}
#character {
width: 10px;
height: 50px;
background-color: transparent;
position: relative;
top: 142px;
}
#obstacle {
width: 20px;
height: 20px;
background-color: transparent;
position: relative;
top: 130px;
left: 450px;
}
.animateJump {
animation: jump 0.5s
}
.animateObstacle {
animation: obstacle 2s infinite linear;
}
#keyframes obstacle {
0%{left: 429px;}
100%{left: -429px;}
}
#keyframes jump {
0%{top: 142px;}
50%{top: 100px;}
100%{top: 142px;}
}
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<script type="text/javascript">
alert("Welcome to Mouse Run! In this game, your goal is to avoid touching the infected cheese. If you do, you lose! Press \"OK\" to start.")
alert("Use LEFT CLICK to jump!")
</script>
<link rel="icon" href="images/thumbnail.png">
<meta charset="utf-8">
<title>Mouse Run</title>
<link rel="stylesheet" href="style.css">
</head>
<body onclick="jump();" style="background-color: lightblue">
<!-- Main Game -->
<p id="title"></p>
<div id="game">
<div id="character"><img class="noselect" src="images/player.png"></div>
<div id="obstacle"><img class="noselect" src="images/obstacle.png" style="height: 20px; width: 50px;"></div>
</div>
<p id="scoreBoard"></p>
</body>
<script type="text/javascript" src="script.js"></script>
</html>
With all this code, I get something like this:
So right now, the character can only jump. I want to give it the ability to dash. My plan was to make a second image for the mouse and swap between that image when the user presses a certain key to dash. The problem is that I don't really know how to swap images in this situation.
So does anyone know how to do this? If you might, please let me know. Any help is appreciated!
Changing the src of the image should work.
function jump() {
let characterImage = character.getElementsByTagName("IMG")[0];
characterImage.src = "images/player_dash.png"; // Path to the new image (change it to the actual name)
setTimeout(function() {
characterImage.src = "images/player.png";
}, 500);
}
You actually dont need the img tag under character div. You can set the background-image of the character div. And change the background-image on .animateJump style.
See the Snippet below:
// Start check
setTimeout(function startobstacles() {
obstacle.classList.add("animateObstacle")
}, 3000);
// Variable definition
var character = document.getElementById('character');
var obstacle = document.getElementById('obstacle');
var score = 0
var dead = false
// Jump movement
function jump() {
character.classList.add("animateJump");
setTimeout(function() {
character.classList.remove("animateJump");
}, 500);
}
// Check if player lost
var checkDead = setInterval(function() {
var characterTop = parseInt(window.getComputedStyle(character).getPropertyValue("top"));
var obstacleLeft = parseInt(window.getComputedStyle(obstacle).getPropertyValue("left"));
if (obstacleLeft < 20 && obstacleLeft > 0 && characterTop >= 130) {
obstacle.style.animation = "none";
obstacle.style.diaplay = "none";
dead = true
//var check = alert("You lost! Your score was " + score + ".");
if (typeof check == 'undefined') {
location.reload();
}
}
}, 10);
// Scoring system
setInterval(function() {
if (dead == false) {
score += 1;
highScore = window.localStorage.getItem('high_score');
if (score > highScore || highScore == null) {
window.localStorage.setItem('high_score', score);
}
highScore = parseInt(window.localStorage.getItem('high_score'));
document.getElementById("scoreBoard").innerHTML = "Your score: " + score + " | Your personal best: " + highScore;
}
}, 2000)
* {
padding: 0;
margin: 0;
}
.noselect {
-webkit-touch-callout: none; /* iOS Safari */
-webkit-user-select: none; /* Safari */
-khtml-user-select: none; /* Konqueror HTML */
-moz-user-select: none; /* Firefox */
-ms-user-select: none; /* Internet Explorer/Edge */
user-select: none; /* Non-prefixed version, currently
supported by Chrome and Opera */
}
#scoreBoard{
font-family: cursive;
font-size: 16px;
}
#game {
width: 500px;
height: 200px;
border: 1px solid black;
background-image: url("https://i.stack.imgur.com/4gZSc.png");
background-size: 107%;
background-repeat: no-repeat;
}
#character {
width: 10px;
height: 50px;
background-color: transparent;
position: relative;
top: 142px;
}
#character{
background-image: url("https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSr7LnFBd0jsRiAUQ7jqerEKt1CujA3yFJFQA&usqp=CAU");
width: 20px;
background-size:contain;
background-repeat: no-repeat;
}
#obstacle {
width: 20px;
height: 20px;
background-color: transparent;
position: relative;
top: 130px;
left: 450px;
}
#character.animateJump {
animation: jump 0.5s;
background-image: url("https://banner2.cleanpng.com/20180616/vvf/kisspng-disco-dance-silhouette-clip-art-bailando-5b2586082d6d97.6157716515291858001861.jpg");
background-size: contain;
}
.animateObstacle {
animation: obstacle 2s infinite linear;
}
#keyframes obstacle {
0%{left: 429px;}
100%{left: -429px;}
}
#keyframes jump {
0%{top: 142px;}
50%{top: 100px;}
100%{top: 142px;}
}
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<script type="text/javascript">
//alert("Welcome to Mouse Run! In this game, your goal is to avoid touching the infected cheese. If you do, you lose! Press \"OK\" to start.")
//alert("Use LEFT CLICK to jump!")
</script>
<link rel="icon" href="images/thumbnail.png">
<meta charset="utf-8">
<title>Mouse Run</title>
<link rel="stylesheet" href="style.css">
</head>
<body onclick="jump();" style="background-color: lightblue">
<!-- Main Game -->
<p id="title"></p>
<div id="game">
<div id="character"></div>
<div id="obstacle"><img class="noselect" src="https://i.stack.imgur.com/XHR5g.png" style="height: 20px;"></div>
</div>
<p id="scoreBoard"></p>
</body>
<script type="text/javascript" src="script.js"></script>
</html>
Look for the comment "Added below lines" and "Added above lines"
You can test it here also.
Related
I want to translateX to a position if change is more than -150, but due to having transition property in container it shows the animation of travelling to the new translate value. I want it to have directly jump to the -400px translateX value without showing the animation to going to it and still have the transition property in place for future scrolls
const config = {
individualItem: '.slide', // class of individual item
carouselWidth: 400, // in px
carouselId: '#slideshow', // carousel selector
carouselHolderId: '#slide-wrapper', // carousel should be <div id="carouselId"><div id="carouselHolderId">{items}</div></div>
}
document.addEventListener("DOMContentLoaded", function(e) {
// Get items
const el = document.querySelector(config.individualItem);
const elWidth = parseFloat(window.getComputedStyle(el).width) + parseFloat(window.getComputedStyle(el).marginLeft) + parseFloat(window.getComputedStyle(el).marginRight);
// Track carousel
let mousedown = false;
let movement = false;
let initialPosition = 0;
let selectedItem;
let currentDelta = 0;
document.querySelectorAll(config.carouselId).forEach(function(item) {
item.style.width = `${config.carouselWidth}px`;
});
document.querySelectorAll(config.carouselId).forEach(function(item) {
item.addEventListener('pointerdown', function(e) {
mousedown = true;
selectedItem = item;
initialPosition = e.pageX;
currentDelta = parseFloat(item.querySelector(config.carouselHolderId).style.transform.split('translateX(')[1]) || 0;
});
});
const scrollCarousel = function(change, currentDelta, selectedItem) {
let numberThatFit = Math.floor(config.carouselWidth / elWidth);
let newDelta = currentDelta + change;
let elLength = selectedItem.querySelectorAll(config.individualItem).length - numberThatFit;
if(newDelta <= 0 && newDelta >= -elWidth * elLength) {
selectedItem.querySelector(config.carouselHolderId).style.transform = `translateX(${newDelta}px)`;
// IMPORTANT LINE
if(newDelta <= 0 && newDelta <= -150) {
selectedItem.querySelector(config.carouselHolderId).style.transform = `translateX(-1000px)`;
}
}
}
document.body.addEventListener('pointermove', function(e) {
if(mousedown == true && typeof selectedItem !== "undefined") {
let change = -(initialPosition - e.pageX);
scrollCarousel(change, currentDelta, document.body);
movement = true;
}
});
['pointerup', 'mouseleave'].forEach(function(item) {
document.body.addEventListener(item, function(e) {
selectedItem = undefined;
movement = false;
});
});
});
.slide-wrapper {
transition: 400ms ease;
transform: translateX(0px);
width: 400px;
height: 400px;
}
.slide-number {
pointer-events: none;
}
<!DOCTYPE html>
<html>
<head>
<title>HTML and CSS Slideshow</title>
<style>
body {
font-family: Helvetica, sans-serif;
padding: 5%;
text-align: center;
font-size: 50;
overflow-x: hidden;
}
/* Styling the area of the slides */
#slideshow {
overflow: hidden;
height: 400px;
width: 400px;
margin: 0 auto;
}
/* Style each of the sides
with a fixed width and height */
.slide {
float: left;
height: 400px;
width: 400px;
}
/* Add animation to the slides */
.slide-wrapper {
/* Calculate the total width on the
basis of number of slides */
width: calc(728px * 4);
/* Specify the animation with the
duration and speed */
/* animation: slide 10s ease infinite; */
}
/* Set the background color
of each of the slides */
.slide:nth-child(1) {
background: green;
}
.slide:nth-child(2) {
background: pink;
}
.slide:nth-child(3) {
background: red;
}
.slide:nth-child(4) {
background: yellow;
}
/* Define the animation
for the slideshow */
#keyframes slide {
/* Calculate the margin-left for
each of the slides */
20% {
margin-left: 0px;
}
40% {
margin-left: calc(-728px * 1);
}
60% {
margin-left: calc(-728px * 2);
}
80% {
margin-left: calc(-728px * 3);
}
}
</style>
</head>
<body>
<!-- Define the slideshow container -->
<div id="slideshow">
<div id="slide-wrapper" class="slide-wrapper">
<!-- Define each of the slides
and write the content -->
<div class="slide">
<h1 class="slide-number">
1
</h1>
</div>
<div class="slide">
<h1 class="slide-number">
2
</h1>
</div>
<div class="slide">
<h1 class="slide-number">
3
</h1>
</div>
<div class="slide">
<h1 class="slide-number">
4
</h1>
</div>
</div>
</div>
</body>
</html>
If I understood your question properly, I think you would have to remove the transition property before changing the value and then apply it again once the transition is done.
const item = selectedItem.querySelector(config.carouselHolderId)
item.style.cssText = `transform: translateX(${newDelta}px); transition: none`;
// Restore the transition
item.style.transition = '';
You could temporarily disable the transition:
const config = {
individualItem: '.slide', // class of individual item
carouselWidth: 400, // in px
carouselId: '#slideshow', // carousel selector
carouselHolderId: '#slide-wrapper', // carousel should be <div id="carouselId"><div id="carouselHolderId">{items}</div></div>
}
document.addEventListener("DOMContentLoaded", function(e) {
// Get items
const el = document.querySelector(config.individualItem);
const elWidth = parseFloat(window.getComputedStyle(el).width) + parseFloat(window.getComputedStyle(el).marginLeft) + parseFloat(window.getComputedStyle(el).marginRight);
// Track carousel
let mousedown = false;
let movement = false;
let initialPosition = 0;
let selectedItem;
let currentDelta = 0;
document.querySelectorAll(config.carouselId).forEach(function(item) {
item.style.width = `${config.carouselWidth}px`;
});
document.querySelectorAll(config.carouselId).forEach(function(item) {
item.addEventListener('pointerdown', function(e) {
mousedown = true;
selectedItem = item;
initialPosition = e.pageX;
currentDelta = parseFloat(item.querySelector(config.carouselHolderId).style.transform.split('translateX(')[1]) || 0;
});
});
const scrollCarousel = function(change, currentDelta, selectedItem) {
let numberThatFit = Math.floor(config.carouselWidth / elWidth);
let newDelta = currentDelta + change;
let elLength = selectedItem.querySelectorAll(config.individualItem).length - numberThatFit;
if(newDelta <= 0 && newDelta >= -elWidth * elLength) {
selectedItem.querySelector(config.carouselHolderId).style.transform = `translateX(${newDelta}px)`;
// IMPORTANT LINE
if(newDelta <= 0 && newDelta <= -150) {
const el = selectedItem.querySelector(config.carouselHolderId);
el.classList.add("jump");
el.style.transform = `translateX(-1000px)`;
setTimeout(() => el.classList.remove("jump"), 10);
}
}
}
document.body.addEventListener('pointermove', function(e) {
if(mousedown == true && typeof selectedItem !== "undefined") {
let change = -(initialPosition - e.pageX);
scrollCarousel(change, currentDelta, document.body);
movement = true;
}
});
['pointerup', 'mouseleave'].forEach(function(item) {
document.body.addEventListener(item, function(e) {
selectedItem = undefined;
movement = false;
});
});
});
.slide-wrapper {
transform: translateX(0px);
width: 400px;
height: 400px;
transition: 400ms ease;
user-select: none;
}
.slide-number {
pointer-events: none;
}
.slide-wrapper.jump
{
transition-duration: 10ms;
}
<!DOCTYPE html>
<html>
<head>
<title>HTML and CSS Slideshow</title>
<style>
body {
font-family: Helvetica, sans-serif;
padding: 5%;
text-align: center;
font-size: 50;
overflow-x: hidden;
}
/* Styling the area of the slides */
#slideshow {
overflow: hidden;
height: 400px;
width: 400px;
margin: 0 auto;
}
/* Style each of the sides
with a fixed width and height */
.slide {
float: left;
height: 400px;
width: 400px;
}
/* Add animation to the slides */
.slide-wrapper {
/* Calculate the total width on the
basis of number of slides */
width: calc(728px * 4);
/* Specify the animation with the
duration and speed */
/* animation: slide 10s ease infinite; */
}
/* Set the background color
of each of the slides */
.slide:nth-child(1) {
background: green;
}
.slide:nth-child(2) {
background: pink;
}
.slide:nth-child(3) {
background: red;
}
.slide:nth-child(4) {
background: yellow;
}
/* Define the animation
for the slideshow */
#keyframes slide {
/* Calculate the margin-left for
each of the slides */
20% {
margin-left: 0px;
}
40% {
margin-left: calc(-728px * 1);
}
60% {
margin-left: calc(-728px * 2);
}
80% {
margin-left: calc(-728px * 3);
}
}
</style>
</head>
<body>
<!-- Define the slideshow container -->
<div id="slideshow">
<div id="slide-wrapper" class="slide-wrapper">
<!-- Define each of the slides
and write the content -->
<div class="slide">
<h1 class="slide-number">
1
</h1>
</div>
<div class="slide">
<h1 class="slide-number">
2
</h1>
</div>
<div class="slide">
<h1 class="slide-number">
3
</h1>
</div>
<div class="slide">
<h1 class="slide-number">
4
</h1>
</div>
</div>
</div>
</body>
</html>
Here is my JSFiddle: https://jsfiddle.net/y6pnq7k5/3/
Sorry if it's too much code, I tried to narrow it down.
The main functions to look at are generatorClicked() and progressBarAnimation().
When you click on the boxes (for example fire spell tome), I have a progress bar animation that goes across the div. The problem is that if you spam click the div it will reset the progress bar back at the start, and because this is meant to be an idle game the progress bar should not be affected until it has finished it's job.
One solution I've tried are disabling pointer events via style:
var isClicked = true;
document.GetElementByID(this.id).style.pointerEvents = 'none';
//progress bar animation - after it's done isClicked = false
if(!isClicked) {
document.GetElementByID(this.id).style.pointerEvents = 'auto';
}
This had issues with either the progress bar not being clickable after the first progress bar finished, or it would still allow the click spam to reset the bar, depending on where I made isClicked false.
I've also tried creating a shield like the top answer in this post
Which just stopped the progress bar from moving at all.
I don't have any libraries, just vanilla JS. I know that my implementation of this progress bar animation is also dubious, but even if I refactor it I still would need the progress bar to not be affected by subsequent clicks as it will affect the gameplay.
pointer-events CSS property can be set to 'none' before the progress bar animation starts and reset to its original value after the progress bar animation stops.
var fireGenerators = ["fireSpellTome", "fireWizard", "fireTeacher", "fireSchool"];
var fireGeneratorStrings = ["Fire Spell Tome", "Fire Wizard", "Fire Teacher", "Fire School"];
var fireGeneratorAmount = new Array();
function initFireGenerators() {
for (i = 0; i < fireGenerators.length; i++) {
fireGeneratorAmount.push(0);
var div = document.createElement('div');
div.id = fireGenerators[i];
div.className = "fireGenerators";
div.innerHTML = fireGeneratorStrings[i];
div.onclick = generatorClicked;
var progressBar = document.createElement('div');
progressBar.id = fireGenerators[i] + "ProgressBar";
progressBar.className = "progressBar";
var amount = document.createElement('span');
amount.id = "amountFireGen" + i;
amount.class = "fireAmounts";
amount.innerHTML = "0";
div.appendChild(progressBar);
div.appendChild(amount);
main.appendChild(div);
}
}
function generatorClicked() {
console.log(this.id + " clicked");
progressBarAnimation(this.id);
}
function progressBarAnimation(parentID) {
const progressBarContainer = document.getElementById(parentID);
const progressBar = document.getElementById(parentID + "ProgressBar"); //Get progressBar div element
let id = null;
let currentWidth = 0; //Set the width to 0
clearInterval(id);
progressBarContainer.style.pointerEvents = "none";
id = setInterval(frame, 10); //TEMPORARY - Need to check what generator and match progress with speed
function frame() {
if (currentWidth == 330) {
clearInterval(id);
progressBar.style.width = "0px";
progressBarContainer.style.pointerEvents = "auto";
} else {
currentWidth++;
progressBar.style.width = currentWidth + "px";
}
}
return true;
}
initFireGenerators();
html, body {
height: 100%;
width: 100%;
margin: 0;
font-family: Arial, Helvetica, sans-serif;
user-select: none;
-webkit-user-select: none;
-moz-user-select: none;
-khtml-user-select: none;
-ms-user-select: none;
}
div span {
margin-left: 15px;
}
#main {
width: 100%;
height: 80%;
}
#fireSpellTome {
background-size: 100% 100%;
background-image: url('../images/firetome.png');
background-repeat: no-repeat;
}
.fireGenerators {
position: relative;
width: 330px;
height: 170px;
border:2px solid #000;
margin-top: 1px;
}
.progressBar {
position: absolute;
top: 0;
width: 0;
height: 100%;
background-color: #111;
opacity: 0.5;
}
.noPointers {
pointer-events: none;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="stylesheets/game.css">
</head>
<body>
<h1><span id="fireMagicAmount">0</span><br></h1>
<div id=main></div>
</body>
</html>
Do you remember that console video game "Guitar Hero"? Or if you are a little younger, "Piano Tiles"?
If you don't know what I'm talking about, click on this link to get an idea = https://www.youtube.com/watch?v=nWLKlEg0VMs&ab_channel=MattSterner
Well, that is exactly what I am doing with this website (on a more basic level of course).
THERE IS NO NEED TO READ THE WHOLE CODE...
What I need your help with:
Look into the JavaScript code and go to the animateFunction() function.
In the if statement you will see I wrote a condition that in human language would be "If I press 'Q key' and the square on the left is where it should be when you get the note right, then console.log(currentNotePosition.bottom);" and that if statement is the same for the notes on the middle line and on the right side.
The issue:
When I click on the keys ('Q', 'W', and 'E'), the console.log(currentNotePosition.bottom) does execute, but it does it sometimes and not when the note is on the spot it should be when I want it to console.log the bottom position. So basically, my code can't detect when a note is at the place where you can score a point.
My theory of the issue:
My code is not able to identify which div/musical_note exactly I want to "score on".
Here is a better place to see and play with my code (tap on the "create" button to start the "game"): https://codepen.io/xavi-font/pen/xxOedzK
(If on the Codepen playground you don't see the "web browser screen" then just pull it up from the bottom, it is a window just like the ones that "contain" the code).
PD: This is written in Vanilla JavaScrpt (No libraries or frameworks).
let speed = 1;
idArray = [];
let topPositionThatAdds = 0;
let squareLeft = {
color: "red",
positionLeft: "250px",
class: 'squareLeft',
}
let squareMiddle = {
color: "green",
positionLeft: "750px",
class: 'squareMiddle',
}
let squareRight = {
color: "yellow",
positionLeft: "1250px",
class: 'squareRight',
}
idList = 0;
randomSquare = [squareLeft, squareMiddle, squareRight];
function generateSquares() {
let randomValue = randomSquare[Math.floor(randomSquare.length * Math.random())];
const newDiv = document.createElement("div");
newDiv.classList.add(randomValue.class);
newDiv.style.top = "-100px";
newDiv.setAttribute("id", idList.toString());
idList++;
idArray.push(idList);
document.body.appendChild(newDiv);
for (let i = 0; i < idArray.length; i++) {
let element = document.getElementById(i.toString());
animateFunction(element);
}
}
function animateFunction(element) {
if (element.style.top == "-100px") {
const interval = setInterval(function() {
element.style.top = eval(parseInt(element.style.top) + 1).toString() + "px";
let currentNotePosition = element.getBoundingClientRect();
document.body.onkeyup = function(e) {
if (e.keyCode == 81 /*Q*/ && currentNotePosition.bottom > 700 && currentNotePosition.bottom < 900 && element.classList.contains('squareLeft')) {
console.log(currentNotePosition.bottom);
}else if (e.keyCode == 87 /*W*/ && currentNotePosition.bottom > 700 && currentNotePosition.bottom < 900 && element.classList.contains('squareMiddle')) {
console.log(currentNotePosition.bottom);
}else if (e.keyCode == 69 /*E*/ && currentNotePosition.bottom > 700 && currentNotePosition.bottom < 900 && element.classList.contains('squareRight')) {
console.log(currentNotePosition.bottom);
}
}
}, speed);
}
}
function startGame() {
let randomGenerationNumber = Math.floor(Math.random() * (500 - 250)) + 250;
const interval = setInterval(generateSquares, randomGenerationNumber);
}
document.getElementById('button').addEventListener("click", startGame);
body{
background: yellow;
padding: 0;
margin: 0;
overflow: hidden;
background-size: cover;
}
#bar{
position: absolute;
bottom: 0;
/* top: 770px; */
height: 100px;
width: 100%;
background: rgb(52,162,162);
background: linear-gradient(90deg, rgba(52,162,162,.25) 0%, rgba(144,28,103,1) 100%);
z-index: 2;
}
.squareRight{
position: absolute;
height: 100px;
width: 100px;
z-index: 1;
left: 250px;
background-size: cover;
background-color: red;
}
.squareMiddle{
position: absolute;
height: 100px;
width: 100px;
z-index: 1;
left: 750px;
background-size: cover;
background-color: green;
}
.squareLeft{
position: absolute;
height: 100px;
width: 100px;
z-index: 1;
left: 1250px;
background-size: cover;
background-color: blue;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>TapTap</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<button id="button">create</button>
<div id="bar"></div>
<script src="app.js"></script>
</body>
</html>
Thank you so much for your time, I hope you can help me with this since its been days and I still can't figure it out.
On another question I asked if I could set the font-weight to bold on a text element when that text is selected. This has been completed much to the avail of #Eric ! But currently, when you click a text, you can happily click another one and both of the text will be bold.
How can I prevent more than one text element from being bold?
Here is my code on JSFiddle: http://jsfiddle.net/6XMzf/ or below:
CSS:
html,body {
margin: 0;
padding: 0
}
#background {
width: 100%;
height: 100%;
position: absolute;
left: 0px;
top: 0px;
z-index: 0;
color: white;
}
.stretch {
width:100%;
height:100%;
}
.navigationPlaceholder {
width:100px;
height: 400px;
left: 100px;
top: 100px;
position: absolute;
}
#navigation {
background-color: #000000;
}
#navigationText ul {
font-family: "Yanone Kaffeesatz";
font-weight: 100;
text-align: left;
font-size: 25px;
color: #b2b2b2;
left: 25px;
top: 50px;
position: absolute;
line-height: 40px;
list-style-type: none;
}
.noSelect {
-moz-user-select: none; /* mozilla browsers */
-khtml-user-select: none; /* webkit browsers */
}
HTML:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>Max Kramer | iOS Developer</title>
<link rel="stylesheet" type="text/css" href="css/style.css" />
<link rel="stylesheet" type="text/css" href="http://fonts.googleapis.com/css?family=Yanone+Kaffeesatz" />
</head>
<body>
<div id="background" />
<div id="navigation" class="navigationPlaceholder">
<div id="navigationText">
<ul>
<li>iOS</li>
<li>Blog</li>
<li>About</li>
<li>Contact</li>
</ul>
</div>
</div>
</div>
<script type="text/javascript">
var nav = document.getElementById('navigationText');
var navItems = nav.getElementsByTagName('li');
for (var i = 0; i < navItems.length; i++) {
navItems[i].addEventListener('click', function() {
this.style.fontWeight = '400';
}, false);
}
</script>
</body>
</html>
If you don't have a selector engine handy like jQuery and really have to do this in plain Javascript, I would do it like this:
function addClass(elem, className) {
if (elem.className.indexOf(className) == -1) {
elem.className += " " + className;
}
}
function removeClass(elem, className) {
elem.className = elem.className.replace(new RegExp("\\s*" + className), "");
}
var lastSelected = null;
function initNavClickHandler() {
var nav = document.getElementById('navigationText');
var navItems = nav.getElementsByTagName('li');
for (var i = 0; i < navItems.length; i++) {
navItems[i].addEventListener('click', function() {
addClass(this, "selected");
if (lastSelected) {
removeClass(lastSelected, "selected");
}
lastSelected = this;
}, false);
}
}
initNavClickHandler();
Then, add a CSS rule that controls the selected look:
.selected {font-weight: 800;}
This is a lot more flexible for styling because you can add as many CSS rules as you want to the .selected class to change/modify it without ever touching your code.
You can see it work here: http://jsfiddle.net/jfriend00/rrxaQ/
If you can use things like jQuery then this is a much simpler problem. Let me show you the jQuery solution for both highlighting and unhighlighting.
$("#navigationText li").click( function() {
$("#navigationText li").css("fontWeight", "100");
$(this).css("fontWeight", "400");
});
Now you can achieve the same thing yourself without jQuery. You either need to create a global that holds the currently bolded item and remove the fontWeight or just remove the fontWeight from all items (brute force).
//untested with global to store currently selected
var nav = document.getElementById('navigationText');
var activeItem = null;
var navItems = nav.getElementsByTagName('li');
for (var i = 0; i < navItems.length; i++) {
navItems[i].addEventListener('click', function() {
if (activeItem) {activeItem.style.fontWeight = '100'; }
this.style.fontWeight = '400';
activeItem = this;
}, false);
}
//sorry I don't feel like writing a brute force one for you!
I have to have many small thumbnails on a page and each one needs to open up to a full size (640x480) video with controls when clicked.
I am surprised no Javascript experts took this. My solution is here:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>PopUp Player using JWPlayer</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<style type="text/css">
input
{
width: 300px;
height: 32px;
font: bold 13px Verdana, serif;
text-align: center;
color: #fe0320;
background: url(player.gif) repeat-x; // 1px wide, 32px high
cursor: pointer;
border: 0;
}
img
{
position: relative;
display: inline-block;
float: left;
border-width: 0;
margin: 0;
padding: 0;
font-size: 0;
cursor: pointer;
z-index: 1;
}
div.clickmecontainer
{
cursor: pointer;
}
div.clickme
{
position: absolute;
display: inline-block;
width: 79px;
top: 50%;
margin-top: -15px;
text-align: center;
color: white;
font-family: Journal;
font-size: 1.5em;
z-index: 2;
}
div.playerpopup
{
position: absolute;
top: 100px;
left: 100px;
z-index: 100;
}
</style>
<script src="http://www.google.com/jsapi"></script>
<script type="text/javascript">google.load('swfobject', '2.2');</script>
<script type="text/javascript">
var swf = false;
function addSwf(file, width, height, id)
{
clearSwf();
if((id != '') && (id != undefined))
{ // alert('The '+gid(id).nodeName+' element with id="' + id + '"\nTop: '+gid(id).style.top + '\nLeft: ' +gid(id).style.left );
gid('playerpopup').style.top = ((gid(id).style.top.replace( 'px', '') * 1) - 500) + 'px';
gid('playerpopup').style.left = ((gid(id).style.left.replace('px', '') * 1) + 60) + 'px';
setTimeout("swf = true;", 1000); // alert('New nTop: '+gid('playerpopup').style.top + '\nLeft: ' +gid('playerpopup').style.left );
}
else
{
gid('playerpopup').style.top = 'px';
gid('playerpopup').style.left = 'px';
setTimeout("swf = true;", 1000);
}
gid('playerpopup').innerHTML='<a id="player"class="player"href="http://www.adobe.com/shockwave/download/download.cgi?P1_Prod_Version=ShockwaveFlash">Adobe Flash Player</a><div><input type="button" style="width:'+width+'px;" value="-- C L O S E --" onclick="clearSwf(); return false;"></div>';
var flashvars =
{
'file': file,
'frontcolor': 'd3d3d3',
'backcolor': '000000',
'lightcolor': '6d6c6b',
'screencolor': '373737',
'id': 'playerID',
'autostart': 'true'
};
var params =
{
'allowfullscreen': 'true',
'allowscriptaccess': 'always',
'wmode': 'opaque',
'bgcolor': '#FFFFFF'
};
var attributes =
{
'id': 'playerID',
'name': 'playerID'
};
swfobject.embedSWF('player.swf', 'player', width, height, '9.0.124', false, flashvars, params, attributes);
};
function clearSwf()
{
if(swf)
{
swfobject.removeSWF('playerID');
gid('playerpopup').innerHTML = '';
swf = false;
}
};
function gid(name)
{
return document.getElementById(name);
};
</script>
</head>
<body bgcolor="white";>
<div id="12345" style=" position:absolute; top:606px; left:120px; width:180px; height:30px; z-index:19;">
<img alt="Preview" src="Preview.jpg" width="80" height="60" onClick="addSwf('video.flv', 640, 503, this.parentNode.getAttribute('id'));" />
</div>
<div id="playerpopup" class="playerpopup"> </div>
</body>
</html>
I suggest using fancybox:
http://fancybox.net/
They have an example with a "swf", I'm sure you can adapt this for your own purposes.
I used Shadowbox.js before and was very pleased with it (video examples are lower on the homepage). You can embed YouTube videos, your own .flv files (using JW Player), Vimeo videos, etc.
Also, it doesn't use any JavaScript framework so it's guaranteed to work with your code.