var api = "https://fcc-weather-api.glitch.me/api/current?";
var lat, lon;
var unit = "C";
var currentTempInCelcius;
$(document).ready(function() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (position) {
var lat = "lat=" + position.coords.latitude;
var lon = "lon=" + position.coords.longitude;
getWeather(lat, lon);
});
} else {
window.alert("Geolocation is not supported by this browser.");
}
$('#unit').click(function () {
var currentUnit = $('#unit').text();
var newUnit = currentUnit == "C" ? "F" : "C";
$('#unit').text(newUnit);
if (newUnit === "F") {
$('#temp').text(Math.round(($('#temp').text() * 1.8) + 32));
} else {
$('#temp').text(Math.round(($('#temp').text() - 32) / 1.8));
}
});
function getWeather(lat, lon) {
var apiUrl = api + lat + "&" + lon;
$.ajax({
url: apiUrl, success: function (result) {
$('#city').text(result.name + ", ");
$('#country').text(result.sys.country);
$('#temp').text(result.main.temp);
$('#unit').text(unit);
$('#currentWeather').text(result.weather[0].main);
$('#desc').text(result.weather[0].description);
addIcon(result.weather[0].main);
}
});
}
function addIcon(weather) {
var now = new Date;
if (now.getHours() + 1 >= 6 && now.getHours() + 1 <= 18) {
$('#icon').removeClass();
switch (weather) {
case 'Clear':
$('#icon').addClass('wi wi-day-sunny');
break;
}
$('.bg').addClass(weather);
} else {
$('#icon').removeClass();
switch (weather) {
case 'Rain':
$('#icon').addClass('wi wi-night-rain');
break;
}
$('.bg').addClass('night' + weather);
}
}
});
#container {
width: 100vw;
height: 100vh;
margin: auto;
position: absolute;
}
p {
font-size: 55px;
margin: 25px 0;
font-family: 'Roboto',
sans-serif;
}
i {
font-size: 65px;
}
.bg {
width: 100vw;
height: 100vh;
opacity: 0.5;
z-index: -10;
}
.Clear {
background: url(https://images.unsplash.com/photo-1501412804587-2a024e482830?auto=format&fit=crop&w=1050&q=60&ixid=dW5zcGxhc2guY29tOzs7Ozs%3D);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container">
<p><span id="city"></span><span id="country"></span></p>
<p><span id="temp"></span><span id="unit"></span></p>
<p id="currentWeather"></p>
<p id="desc"></p>
<i id="icon"></i>
</div>
<div class="bg"></div>
I am making a local weather app.
I want to make the unit change when the click event is executed.
However, since I added the element, it doesn't work.
I used the .bg tag to add a background to it, so every time the weather changes, the background will also change.
I guess it is because the .bg div covered the #container div. so I tried z-index, but it still doesn't work.
What can I do to make it work?
Thank you :)
Change the position Relative for the container that is masking the click event. Below is the working solution.
var api = "https://fcc-weather-api.glitch.me/api/current?";
var lat, lon;
var unit = "C";
var currentTempInCelcius;
$(document).ready(function() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (position) {
var lat = "lat=" + position.coords.latitude;
var lon = "lon=" + position.coords.longitude;
getWeather(lat, lon);
});
} else {
window.alert("Geolocation is not supported by this browser.");
}
$('#unit').click(function () {
var currentUnit = $('#unit').text();
var newUnit = currentUnit == "C" ? "F" : "C";
$('#unit').text(newUnit);
if (newUnit === "F") {
$('#temp').text(Math.round(($('#temp').text() * 1.8) + 32));
} else {
$('#temp').text(Math.round(($('#temp').text() - 32) / 1.8));
}
});
function getWeather(lat, lon) {
var apiUrl = api + lat + "&" + lon;
$.ajax({
url: apiUrl, success: function (result) {
$('#city').text(result.name + ", ");
$('#country').text(result.sys.country);
$('#temp').text(result.main.temp);
$('#unit').text(unit);
$('#currentWeather').text(result.weather[0].main);
$('#desc').text(result.weather[0].description);
addIcon(result.weather[0].main);
}
});
}
function addIcon(weather) {
var now = new Date;
if (now.getHours() + 1 >= 6 && now.getHours() + 1 <= 18) {
$('#icon').removeClass();
switch (weather) {
case 'Clear':
$('#icon').addClass('wi wi-day-sunny');
break;
}
$('.bg').addClass(weather);
} else {
$('#icon').removeClass();
switch (weather) {
case 'Rain':
$('#icon').addClass('wi wi-night-rain');
break;
}
$('.bg').addClass('night' + weather);
}
}
});
#container{
width: 20%;
height: 20%;
margin: auto;
}
p {
font-size: 55px;
margin: 25px 0;
font-family: 'Roboto',
sans-serif;}
i {
font-size: 65px; }
.bg {
width: 100vw;
height: 100vh;
opacity: 0.5;
z-index: 1; }
.Clear {
background: url(https://images.unsplash.com/photo-1501412804587-2a024e482830?auto=format&fit=crop&w=1050&q=60&ixid=dW5zcGxhc2guY29tOzs7Ozs%3D) ; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container">
<p><span id="city"></span><span id="country"></span></p>
<p><span id="temp"></span><span id="unit"></span></p>
<p id="currentWeather"></p>
<p id="desc"></p>
<i id="icon"></i>
</div>
<div class="bg"></div>
Hi remove position: absolute from #container and add some text to #unit span/ add some properties to it (as per your requirement).
#unit {
width: 50px;
height: 50px;
display: inline-block;
}
In your situation, you could remove position: absolute from #container and add it to .bg followed with top:0;left:0, check the updated snippet below:
var api = "https://fcc-weather-api.glitch.me/api/current?";
var lat, lon;
var unit = "C";
var currentTempInCelcius;
$(document).ready(function() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (position) {
var lat = "lat=" + position.coords.latitude;
var lon = "lon=" + position.coords.longitude;
getWeather(lat, lon);
});
} else {
window.alert("Geolocation is not supported by this browser.");
}
$('#unit').click(function () {
var currentUnit = $('#unit').text();
var newUnit = currentUnit == "C" ? "F" : "C";
$('#unit').text(newUnit);
if (newUnit === "F") {
$('#temp').text(Math.round(($('#temp').text() * 1.8) + 32));
} else {
$('#temp').text(Math.round(($('#temp').text() - 32) / 1.8));
}
});
function getWeather(lat, lon) {
var apiUrl = api + lat + "&" + lon;
$.ajax({
url: apiUrl, success: function (result) {
$('#city').text(result.name + ", ");
$('#country').text(result.sys.country);
$('#temp').text(result.main.temp);
$('#unit').text(unit);
$('#currentWeather').text(result.weather[0].main);
$('#desc').text(result.weather[0].description);
addIcon(result.weather[0].main);
}
});
}
function addIcon(weather) {
var now = new Date;
if (now.getHours() + 1 >= 6 && now.getHours() + 1 <= 18) {
$('#icon').removeClass();
switch (weather) {
case 'Clear':
$('#icon').addClass('wi wi-day-sunny');
break;
}
$('.bg').addClass(weather);
} else {
$('#icon').removeClass();
switch (weather) {
case 'Rain':
$('#icon').addClass('wi wi-night-rain');
break;
}
$('.bg').addClass('night' + weather);
}
}
});
#container { width: 100vw; height: 100vh; margin: auto; }
p { font-size: 55px; margin: 25px 0; font-family: 'Roboto', sans-serif;}
i { font-size: 65px; }
.bg { width: 100vw;position: absolute;top:0;left:0; height: 100vh; opacity: 0.5; z-index: -10; }
.Clear { background: url(https://images.unsplash.com/photo-1501412804587-2a024e482830?auto=format&fit=crop&w=1050&q=60&ixid=dW5zcGxhc2guY29tOzs7Ozs%3D) ; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container">
<p><span id="city"></span><span id="country"></span></p>
<p><span id="temp"></span><span id="unit"></span></p>
<p id="currentWeather"></p>
<p id="desc"></p>
<i id="icon"></i>
</div>
<div class="bg"></div>
Related
I hope you can give me a hand with this. My idea is to show a list of high-scores after the game is finished for a Doodle Jump project (javascript). The high-scores are presented successfully as you will see in my code, but the presentation is poor. Hence, I want to show them in a blank page, if possible using the same html. I will leave my code for you to reproduce the issue and help me. I thought about some document command, but you tell me.
Thanks in advance.
document.addEventListener('DOMContentLoaded', () => {
const grid = document.querySelector('.grid')
const doodler = document.createElement('div')
const unMutedIcon = document.createElement('div')
let doodlerLeftSpace = 50
let startPoint = 150
let doodlerBottomSpace = startPoint
let isGameOver = false
let platformCount = 5
let platforms = []
let upTimerid
let downTimerId
let isJumping = true
let isGoingLeft = false
let isGoingRight = false
let leftTimerId
let rightTimerId
let score = 0
let context
let musicIsPlaying = false
let copyRightMessage = " DoodleJump version by Santiago Hernandez \n all rights reserved \n Copyright © "
const NO_OF_HIGH_SCORES = 10;
const HIGH_SCORES = 'highScores';
function createDoodler() {
grid.appendChild(doodler)
doodler.classList.add('doodler')
doodlerLeftSpace = platforms[0].left
doodler.style.left = doodlerLeftSpace + 'px'
doodler.style.bottom = doodlerBottomSpace + 'px'
}
function control(e) {
if (e.key === "ArrowLeft") {
moveLeft()
} else if (e.key === "ArrowRight") {
moveRight()
} else if (e.key === "ArrowUp") {
moveStraight()
}
}
class Platform {
constructor(newPlatBottom) {
this.bottom = newPlatBottom
this.left = Math.random() * 315
this.visual = document.createElement('div')
const visual = this.visual
visual.classList.add('platform')
visual.style.left = this.left + 'px'
visual.style.bottom = this.bottom + 'px'
grid.appendChild(visual)
}
}
function createPlatforms() {
for (let i = 0; i < platformCount; i++) {
let platGap = 600 / platformCount
let newPlatBottom = 100 + i * platGap
let newPlatform = new Platform(newPlatBottom)
platforms.push(newPlatform)
console.log(platforms)
}
}
function movePlatforms() {
if (doodlerBottomSpace > 200) {
platforms.forEach(platform => {
platform.bottom -= 4
let visual = platform.visual
visual.style.bottom = platform.bottom + 'px'
if (platform.bottom < 10) {
let firstPlatform = platforms[0].visual
firstPlatform.classList.remove('platform')
platforms.shift()
score++
console.log(score)
console.log(platforms)
let newPlatform = new Platform(600)
platforms.push(newPlatform)
}
})
}
}
function jump() {
clearInterval(downTimerId)
isJumping = true
upTimerId = setInterval(function() {
doodlerBottomSpace += 20
doodler.style.bottom = doodlerBottomSpace + 'px'
if (doodlerBottomSpace > startPoint + 200) {
fall()
}
}, 30)
}
function fall() {
clearInterval(upTimerId)
isJumping = false
downTimerId = setInterval(function() {
doodlerBottomSpace -= 5
doodler.style.bottom = doodlerBottomSpace + 'px'
if (doodlerBottomSpace <= 0) {
gameOver()
}
platforms.forEach(platform => {
if ((doodlerBottomSpace >= platform.bottom) &&
(doodlerBottomSpace <= platform.bottom + 15) &&
((doodlerLeftSpace + 60) >= platform.left) &&
(doodlerLeftSpace <= (platform.left + 85)) &&
!isJumping
) {
console.log('landed')
startPoint = doodlerBottomSpace
jump()
}
})
}, 30)
}
function moveLeft() {
if (isGoingRight) {
clearInterval(rightTimerId)
isGoingRight = false
}
isGoingLeft = true
leftTimerId = setInterval(function() {
if (doodlerLeftSpace >= 0) {
doodlerLeftSpace -= 5
doodler.style.left = doodlerLeftSpace + 'px'
} else moveRight()
}, 30)
}
function moveRight() {
if (isGoingLeft) {
clearInterval(leftTimerId)
isGoingLeft = false
}
isGoingRight = true
rightTimerId = setInterval(function() {
if (doodlerLeftSpace <= 340) {
doodlerLeftSpace += 5
doodler.style.left = doodlerLeftSpace + 'px'
} else moveLeft()
}, 30)
}
function moveStraight() {
isGoingRight = false
isGoingLeft = false
clearInterval(rightTimerId)
clearInterval(leftTimerId)
}
function gameOver() {
console.log('GAME OVER')
isGameOver = true
try {
context.pause()
while (grid.firstChild) {
grid.removeChild(grid.firstChild)
}
grid.innerHTML = score
clearInterval(upTimerId)
clearInterval(downTimerId)
clearInterval(leftTimerId)
clearInterval(rightTimerId)
} catch (err) {
console.log('there was an error at gameover')
while (grid.firstChild) {
grid.removeChild(grid.firstChild)
}
grid.innerHTML = score
clearInterval(upTimerId)
clearInterval(downTimerId)
clearInterval(leftTimerId)
clearInterval(rightTimerId)
}
checkHighScore()
}
function saveHighScore(score, highScores) {
const name = prompt('You got a highscore! Enter name:');
const newScore = {
score,
name
};
// 1. Add to list
highScores.push(newScore);
// 2. Sort the list
highScores.sort((a, b) => b.score - a.score);
// 3. Select new list
highScores.splice(NO_OF_HIGH_SCORES);
// 4. Save to local storage
localStorage.setItem(HIGH_SCORES, JSON.stringify(highScores));
};
function checkHighScore() {
const highScores = JSON.parse(localStorage.getItem(HIGH_SCORES)) ? ? [];
const lowestScore = highScores[NO_OF_HIGH_SCORES - 1] ? .score ? ? 0;
if (score > lowestScore) {
saveHighScore(score, highScores); // TODO
showHighScores(); // TODO
}
}
function showHighScores() {
const highScores = JSON.parse(localStorage.getItem(HIGH_SCORES)) ? ? [];
const highScoreList = document.getElementById('highScores');
highScoreList.innerHTML = highScores.map((score) =>
`<li>${score.score} - ${score.name}</li>`
);
}
function start() {
if (!isGameOver) {
createPlatforms()
createDoodler()
setInterval(movePlatforms, 30)
jump()
document.addEventListener('keyup', control)
}
}
document.addEventListener('keypressed', control)
//attach to buttom
start()
//event listener to play music
document.addEventListener('keypress', function(e) {
if (e.keyCode == 32 || e.code == "Space") {
musicIsPlaying = true
context = new Audio("Music_level1.wav");
context.play()
context.loop = true
}
}) //end of event listener
})
.grid {
width: 400px;
height: 600px;
background-color: yellow;
position: relative;
font-size: 200px;
text-align: center;
background-image: url(bluesky_level1.gif);
background-size: contain;
background-repeat: no-repeat;
background-size: 400px 600px;
margin-right: auto;
margin-left: auto;
}
.doodler {
width: 60px;
height: 85px;
position: absolute;
background-image: url(mariobros_level1.png);
background-size: contain;
background-repeat: no-repeat;
background-size: 60px 85px;
filter: brightness(1.1);
mix-blend-mode: multiply;
}
#audio {
display: none
}
.platform {
width: 85px;
height: 15px;
position: absolute;
background-image: url(platform_tramp_level1.png);
background-size: contain;
background-repeat: no-repeat;
background-size: 85px 15px;
}
.volumeIcon {
width: 30px;
height: 30px;
position: absolute;
top: 570px;
background-image: url(volumeIconMuted.png);
background-size: contain;
background-repeat: no-repeat;
background-size: 30px 30px;
}
.unmutedIcon {
width: 30px;
height: 30px;
position: absolute;
top: 570px;
background-image: url(VolumeIcon.png);
background-size: contain;
background-repeat: no-repeat;
background-size: 30px 30px;
}
#highScores {
width: 400px;
height: 300px;
font-size: 30px;
font-family: "Georgia", "Times New Roman";
text-align: center;
position: absolute;
}
<ol id="highScores"></ol>
<div class="grid">
<div class="volumeIcon"></div>
</div>
I included what I think will reproduce the situation. Hope this helps you help me.
Why not just put:
<ol id = "highScores"></ol>
within a <div> and give that a class that has display: none initally? Like this:
<div class="high-scores-container">
<ol id = "highScores"></ol>
</div>
.high-scores-container {
display: none;
height: 100%;
}
Then when you run your showHighScores() function, grab the high-scores-container div and change the display to block and then at the same time, grab the grid div and set that to display: none. That will give you the effect of displaying your high scores on a separate page but you're just doing so with JS/CSS.
The requirement is to sow the information continuously hence opted for a ticker style.
Now I am using an [ticker-style.css] along with [jquery.ticker.js]
It works fine in a Full Screen however while browsing in a Mobile/Tabler - the text is getting cut (see below screenshot) - I tried to play around the width however the rendering was not as expected.
Can you help here.
Thanks in advance.
/*
jQuery News Ticker is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, version 2 of the License.
jQuery News Ticker is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with jQuery News Ticker. If not, see <http://www.gnu.org/licenses/>.
*/
(function($){
$.fn.ticker = function(options) {
// Extend our default options with those provided.
// Note that the first arg to extend is an empty object -
// this is to keep from overriding our "defaults" object.
var opts = $.extend({}, $.fn.ticker.defaults, options);
// check that the passed element is actually in the DOM
if ($(this).length == 0) {
if (window.console && window.console.log) {
window.console.log('Element does not exist in DOM!');
}
else {
alert('Element does not exist in DOM!');
}
return false;
}
/* Get the id of the UL to get our news content from */
var newsID = '#' + $(this).attr('id');
/* Get the tag type - we will check this later to makde sure it is a UL tag */
var tagType = $(this).get(0).tagName;
return this.each(function() {
// get a unique id for this ticker
var uniqID = getUniqID();
/* Internal vars */
var settings = {
position: 0,
time: 0,
distance: 0,
newsArr: {},
play: true,
paused: false,
contentLoaded: false,
dom: {
contentID: '#ticker-content-' + uniqID,
titleID: '#ticker-title-' + uniqID,
titleElem: '#ticker-title-' + uniqID + ' SPAN',
tickerID : '#ticker-' + uniqID,
wrapperID: '#ticker-wrapper-' + uniqID,
revealID: '#ticker-swipe-' + uniqID,
revealElem: '#ticker-swipe-' + uniqID + ' SPAN',
controlsID: '#ticker-controls-' + uniqID,
prevID: '#prev-' + uniqID,
nextID: '#next-' + uniqID,
playPauseID: '#play-pause-' + uniqID
}
};
// if we are not using a UL, display an error message and stop any further execution
if (tagType != 'UL' && tagType != 'OL' && opts.htmlFeed === true) {
debugError('Cannot use <' + tagType.toLowerCase() + '> type of element for this plugin - must of type <ul> or <ol>');
return false;
}
// set the ticker direction
opts.direction == 'rtl' ? opts.direction = 'right' : opts.direction = 'left';
// lets go...
initialisePage();
/* Function to get the size of an Object*/
function countSize(obj) {
var size = 0, key;
for (key in obj) {
if (obj.hasOwnProperty(key)) size++;
}
return size;
};
function getUniqID() {
var newDate = new Date;
return newDate.getTime();
}
/* Function for handling debug and error messages */
function debugError(obj) {
if (opts.debugMode) {
if (window.console && window.console.log) {
window.console.log(obj);
}
else {
alert(obj);
}
}
}
/* Function to setup the page */
function initialisePage() {
// process the content for this ticker
processContent();
// add our HTML structure for the ticker to the DOM
$(newsID).wrap('<div id="' + settings.dom.wrapperID.replace('#', '') + '"></div>');
// remove any current content inside this ticker
$(settings.dom.wrapperID).children().remove();
$(settings.dom.wrapperID).append('<div id="' + settings.dom.tickerID.replace('#', '') + '" class="ticker"><div id="' + settings.dom.titleID.replace('#', '') + '" class="ticker-title"><span><!-- --></span></div><p id="' + settings.dom.contentID.replace('#', '') + '" class="ticker-content"></p><div id="' + settings.dom.revealID.replace('#', '') + '" class="ticker-swipe"><span><!-- --></span></div></div>');
$(settings.dom.wrapperID).removeClass('no-js').addClass('ticker-wrapper has-js ' + opts.direction);
// hide the ticker
$(settings.dom.tickerElem + ',' + settings.dom.contentID).hide();
// add the controls to the DOM if required
if (opts.controls) {
// add related events - set functions to run on given event
$(settings.dom.controlsID).on('click mouseover mousedown mouseout mouseup', function (e) {
var button = e.target.id;
if (e.type == 'click') {
switch (button) {
case settings.dom.prevID.replace('#', ''):
// show previous item
settings.paused = true;
$(settings.dom.playPauseID).addClass('paused');
manualChangeContent('prev');
break;
case settings.dom.nextID.replace('#', ''):
// show next item
settings.paused = true;
$(settings.dom.playPauseID).addClass('paused');
manualChangeContent('next');
break;
case settings.dom.playPauseID.replace('#', ''):
// play or pause the ticker
if (settings.play == true) {
settings.paused = true;
$(settings.dom.playPauseID).addClass('paused');
pauseTicker();
}
else {
settings.paused = false;
$(settings.dom.playPauseID).removeClass('paused');
restartTicker();
}
break;
}
}
else if (e.type == 'mouseover' && $('#' + button).hasClass('controls')) {
$('#' + button).addClass('over');
}
else if (e.type == 'mousedown' && $('#' + button).hasClass('controls')) {
$('#' + button).addClass('down');
}
else if (e.type == 'mouseup' && $('#' + button).hasClass('controls')) {
$('#' + button).removeClass('down');
}
else if (e.type == 'mouseout' && $('#' + button).hasClass('controls')) {
$('#' + button).removeClass('over');
}
});
// add controls HTML to DOM
$(settings.dom.wrapperID).append('<ul id="' + settings.dom.controlsID.replace('#', '') + '" class="ticker-controls"><li id="' + settings.dom.playPauseID.replace('#', '') + '" class="jnt-play-pause controls"><!-- --></li><li id="' + settings.dom.prevID.replace('#', '') + '" class="jnt-prev controls"><!-- --></li><li id="' + settings.dom.nextID.replace('#', '') + '" class="jnt-next controls"><!-- --></li></ul>');
}
if (opts.displayType != 'fade') {
// add mouse over on the content
$(settings.dom.contentID).mouseover(function () {
if (settings.paused == false) {
pauseTicker();
}
}).mouseout(function () {
if (settings.paused == false) {
restartTicker();
}
});
}
// we may have to wait for the ajax call to finish here
if (!opts.ajaxFeed) {
setupContentAndTriggerDisplay();
}
}
/* Start to process the content for this ticker */
function processContent() {
// check to see if we need to load content
if (settings.contentLoaded == false) {
// construct content
if (opts.ajaxFeed) {
if (opts.feedType == 'xml') {
$.ajax({
url: opts.feedUrl,
cache: false,
dataType: opts.feedType,
async: true,
success: function(data){
count = 0;
// get the 'root' node
for (var a = 0; a < data.childNodes.length; a++) {
if (data.childNodes[a].nodeName == 'rss') {
xmlContent = data.childNodes[a];
}
}
// find the channel node
for (var i = 0; i < xmlContent.childNodes.length; i++) {
if (xmlContent.childNodes[i].nodeName == 'channel') {
xmlChannel = xmlContent.childNodes[i];
}
}
// for each item create a link and add the article title as the link text
for (var x = 0; x < xmlChannel.childNodes.length; x++) {
if (xmlChannel.childNodes[x].nodeName == 'item') {
xmlItems = xmlChannel.childNodes[x];
var title, link = false;
for (var y = 0; y < xmlItems.childNodes.length; y++) {
if (xmlItems.childNodes[y].nodeName == 'title') {
title = xmlItems.childNodes[y].lastChild.nodeValue;
}
else if (xmlItems.childNodes[y].nodeName == 'link') {
link = xmlItems.childNodes[y].lastChild.nodeValue;
}
if ((title !== false && title != '') && link !== false) {
settings.newsArr['item-' + count] = { type: opts.titleText, content: '' + title + '' }; count++; title = false; link = false;
}
}
}
}
// quick check here to see if we actually have any content - log error if not
if (countSize(settings.newsArr < 1)) {
debugError('Couldn\'t find any content from the XML feed for the ticker to use!');
return false;
}
settings.contentLoaded = true;
setupContentAndTriggerDisplay();
}
});
}
else {
debugError('Code Me!');
}
}
else if (opts.htmlFeed) {
if($(newsID + ' LI').length > 0) {
$(newsID + ' LI').each(function (i) {
// maybe this could be one whole object and not an array of objects?
settings.newsArr['item-' + i] = { type: opts.titleText, content: $(this).html()};
});
}
else {
debugError('Couldn\'t find HTML any content for the ticker to use!');
return false;
}
}
else {
debugError('The ticker is set to not use any types of content! Check the settings for the ticker.');
return false;
}
}
}
function setupContentAndTriggerDisplay() {
settings.contentLoaded = true;
// update the ticker content with the correct item
// insert news content into DOM
$(settings.dom.titleElem).html(settings.newsArr['item-' + settings.position].type);
$(settings.dom.contentID).html(settings.newsArr['item-' + settings.position].content);
// set the next content item to be used - loop round if we are at the end of the content
if (settings.position == (countSize(settings.newsArr) -1)) {
settings.position = 0;
}
else {
settings.position++;
}
// get the values of content and set the time of the reveal (so all reveals have the same speed regardless of content size)
distance = $(settings.dom.contentID).width();
time = distance / opts.speed;
// start the ticker animation
revealContent();
}
// slide back cover or fade in content
function revealContent() {
$(settings.dom.contentID).css('opacity', '1');
if(settings.play) {
// get the width of the title element to offset the content and reveal
var offset = $(settings.dom.titleID).width() + 20;
$(settings.dom.revealID).css(opts.direction, offset + 'px');
// show the reveal element and start the animation
if (opts.displayType == 'fade') {
// fade in effect ticker
$(settings.dom.revealID).hide(0, function () {
$(settings.dom.contentID).css(opts.direction, offset + 'px').fadeIn(opts.fadeInSpeed, postReveal);
});
}
else if (opts.displayType == 'scroll') {
// to code
}
else {
// default bbc scroll effect
$(settings.dom.revealElem).show(0, function () {
$(settings.dom.contentID).css(opts.direction, offset + 'px').show();
// set our animation direction
animationAction = opts.direction == 'right' ? { marginRight: distance + 'px'} : { marginLeft: distance + 'px' };
$(settings.dom.revealID).css('margin-' + opts.direction, '0px').delay(20).animate(animationAction, time, 'linear', postReveal);
});
}
}
else {
return false;
}
};
// here we hide the current content and reset the ticker elements to a default state ready for the next ticker item
function postReveal() {
if(settings.play) {
// we have to separately fade the content out here to get around an IE bug - needs further investigation
$(settings.dom.contentID).delay(opts.pauseOnItems).fadeOut(opts.fadeOutSpeed);
// deal with the rest of the content, prepare the DOM and trigger the next ticker
if (opts.displayType == 'fade') {
$(settings.dom.contentID).fadeOut(opts.fadeOutSpeed, function () {
$(settings.dom.wrapperID)
.find(settings.dom.revealElem + ',' + settings.dom.contentID)
.hide()
.end().find(settings.dom.tickerID + ',' + settings.dom.revealID)
.show()
.end().find(settings.dom.tickerID + ',' + settings.dom.revealID)
.removeAttr('style');
setupContentAndTriggerDisplay();
});
}
else {
$(settings.dom.revealID).hide(0, function () {
$(settings.dom.contentID).fadeOut(opts.fadeOutSpeed, function () {
$(settings.dom.wrapperID)
.find(settings.dom.revealElem + ',' + settings.dom.contentID)
.hide()
.end().find(settings.dom.tickerID + ',' + settings.dom.revealID)
.show()
.end().find(settings.dom.tickerID + ',' + settings.dom.revealID)
.removeAttr('style');
setupContentAndTriggerDisplay();
});
});
}
}
else {
$(settings.dom.revealElem).hide();
}
}
// pause ticker
function pauseTicker() {
settings.play = false;
// stop animation and show content - must pass "true, true" to the stop function, or we can get some funky behaviour
$(settings.dom.tickerID + ',' + settings.dom.revealID + ',' + settings.dom.titleID + ',' + settings.dom.titleElem + ',' + settings.dom.revealElem + ',' + settings.dom.contentID).stop(true, true);
$(settings.dom.revealID + ',' + settings.dom.revealElem).hide();
$(settings.dom.wrapperID)
.find(settings.dom.titleID + ',' + settings.dom.titleElem).show()
.end().find(settings.dom.contentID).show();
}
// play ticker
function restartTicker() {
settings.play = true;
settings.paused = false;
// start the ticker again
postReveal();
}
// change the content on user input
function manualChangeContent(direction) {
pauseTicker();
switch (direction) {
case 'prev':
if (settings.position == 0) {
settings.position = countSize(settings.newsArr) -2;
}
else if (settings.position == 1) {
settings.position = countSize(settings.newsArr) -1;
}
else {
settings.position = settings.position - 2;
}
$(settings.dom.titleElem).html(settings.newsArr['item-' + settings.position].type);
$(settings.dom.contentID).html(settings.newsArr['item-' + settings.position].content);
break;
case 'next':
$(settings.dom.titleElem).html(settings.newsArr['item-' + settings.position].type);
$(settings.dom.contentID).html(settings.newsArr['item-' + settings.position].content);
break;
}
// set the next content item to be used - loop round if we are at the end of the content
if (settings.position == (countSize(settings.newsArr) -1)) {
settings.position = 0;
}
else {
settings.position++;
}
}
});
};
// plugin defaults - added as a property on our plugin function
$.fn.ticker.defaults = {
speed: 0.10,
ajaxFeed: false,
feedUrl: '',
feedType: 'xml',
displayType: 'reveal',
htmlFeed: true,
debugMode: true,
controls: true,
titleText: '',
direction: 'ltr',
pauseOnItems: 3000,
fadeInSpeed: 600,
fadeOutSpeed: 300
};
})(jQuery);
/* Ticker Styling */
.ticker-wrapper.has-js {
margin: 0;
padding: 0;
width: 780px;
height: 32px;
display: block;
-webkit-border-radius: 15px;
-moz-border-radius: 15px;
border-radius: 15px;
background-color:inherit;
font-size: inherit;
}
.ticker {
width: 710px;
height: 23px;
display: block;
position: relative;
overflow: hidden;
background-color: #fff;
#media #{$xs}{
width: 200px;
}
}
.ticker-title {
padding-top: 9px;
color: #990000;
font-weight: bold;
background-color: #fff;
text-transform: capitalize;
}
.ticker-content {
margin: 0px;
/* padding-top: 9px; */
position: absolute;
color: #506172;
font-weight: normal;
background-color: #fff;
overflow: hidden;
white-space: nowrap;
font-family: "Roboto",sans-serif;
font-size: 16px;
}
.ticker-content:focus {
none;
}
.ticker-content a {
text-decoration: none;
color: #1F527B;
}
.ticker-content a:hover {
text-decoration: underline;
color: #0D3059;
}
.ticker-swipe {
padding-top: 9px;
position: absolute;
top: 0px;
background-color: #fff;
display: block;
width: 800px;
height: 23px;
}
.ticker-swipe span {
margin-left: 1px;
background-color: #fff;
border-bottom: 1px solid #1F527B;
height: 12px;
width: 7px;
display: block;
}
.ticker-controls {
padding: 8px 0px 0px 0px;
list-style-type: none;
float: left;
}
.ticker-controls li {
padding: 0px;
margin-left: 5px;
float: left;
cursor: pointer;
height: 16px;
width: 16px;
display: block;
}
.ticker-controls li.jnt-play-pause {
background-image: url('../images/controls.png');
background-position: 32px 16px;
}
.ticker-controls li.jnt-play-pause.over {
background-position: 32px 32px;
}
.ticker-controls li.jnt-play-pause.down {
background-position: 32px 0px;
}
.ticker-controls li.jnt-play-pause.paused {
background-image: url('../images/controls.png');
background-position: 48px 16px;
}
.ticker-controls li.jnt-play-pause.paused.over {
background-position: 48px 32px;
}
.ticker-controls li.jnt-play-pause.paused.down {
background-position: 48px 0px;
}
.ticker-controls li.jnt-prev {
background-image: url('../images/controls.png');
background-position: 0px 16px;
}
.ticker-controls li.jnt-prev.over {
background-position: 0px 32px;
}
.ticker-controls li.jnt-prev.down {
background-position: 0px 0px;
}
.ticker-controls li.jnt-next {
background-image: url('../images/controls.png');
background-position: 16px 16px;
}
.ticker-controls li.jnt-next.over {
background-position: 16px 32px;
}
.ticker-controls li.jnt-next.down {
background-position: 16px 0px;
}
.js-hidden {
display: none;
}
.no-js-news {
padding: 10px 0px 0px 45px;
color: #fff;
}
.left .ticker-swipe {
/*left: 80px;*/
}
.left .ticker-controls, .left .ticker-content, .left .ticker-title, .left .ticker {
float: left;
}
.left .ticker-controls {
padding-left: 6px;
}
.right .ticker-swipe {
/*right: 80px;*/
}
.right .ticker-controls, .right .ticker-content, .right .ticker-title, .right .ticker {
float: right;
}
.right .ticker-controls {
padding-right: 6px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<strong>Trending now</strong>
<!-- <p>Rem ipsum dolor sit amet, consectetur adipisicing elit.</p> -->
<div class="trending-animated">
<ul id="js-news" class="js-hidden">
<li class="news-item">Dolor sit amet, consectetur adipisicing elit.</li>
<li class="news-item">Spondon IT sit amet, consectetur.......</li>
<li class="news-item">Rem ipsum dolor sit amet, consectetur adipisicing elit.</li>
</ul>
</div>
The problem is that you are setting fixed widths for ticker elements.The ticker container has a width of 720px no matter what size the screen, and on screens < 767px the container for the scrolling text is just 230px.
Either change the CSS if it is your own, or if not you can add these rules after the Ticker CSS in included:
#media (max-width: 767px){
.ticker-wrapper.has-js,
.ticker,
.trending-tittle .ticker {
width: 100%!important;
}
}
This sets them to use the full width of the screen.
I have working but ugly solution.
Idea is:
Run progress bar before ajax call
Jump to end of progress bar when complete (or fail)
Wait at 90% if ajax call is not finished yet (when finish than jump to end)
There are at least three problems in my solution:
I have to reset progress bar 'width' in 3 places.
I must have public variable (widthProgressBar)
I cannot reuse function 'startProgress' in case I want to have two progress bars at same page.
This is my solution: http://jsfiddle.net/WQXXT/5403/
var widthProgressBarPing = 0;
// handles the click event, sends the query
function getSuccessOutput() {
widthProgressBar = 0;
startProgress("pingTestBar");
$.ajax({
url: '/echo/js/?js=hello%20world!',
complete: function(response) {
widthProgressBar = 99;
},
error: function() {
widthProgressBar = 99;
},
});
return false;
}
function startProgress(barId) {
var elem = document.getElementById(barId);
var id = setInterval(frame, 15);
function frame() {
if (widthProgressBar >= 90 && widthProgressBar < 99) {}
if (widthProgressBar >= 100) {
clearInterval(id);
} else {
widthProgressBar++;
elem.style.width = widthProgressBar + '%';
elem.innerHTML = widthProgressBar * 1 + '%';
}
}
}
.testProgress {
width: 100%;
background-color: #ddd;
}
.testProgressBar {
width: 0%;
height: 30px;
background-color: #4CAF50;
text-align: center;
line-height: 30px;
color: white;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
test success |
<div class="testProgress">
<div id="pingTestBar" class="testProgressBar"></div>
</div>
I believe this is the right approach, without changing unnecessary variables outside usage scope.
// handles the click event, sends the query
function getSuccessOutput() {
var bar = new Bar("pingTestBar");
$.ajax({
url: '/echo/js/?js=hello%20world!',
complete: function(response) {
bar.finish()
},
error: function() {
bar.finish()
},
});
return false;
}
function Bar(barId) {
var self = this;
self.w = 0;
var elem = document.getElementById(barId);
var id = setInterval(frame, 15);
this.finish = function(){
clearInterval(id);
self.w = 100;
changeElem()
}
function changeElem(){
elem.style.width = self.w + '%';
elem.innerHTML = self.w * 1 + '%';
}
function frame() {
if (self.w >= 90 && self.w < 99) {}
if (self.w >= 100) {
} else {
self.w++;
changeElem()
}
}
}
.testProgress {
width: 100%;
background-color: #ddd;
}
.testProgressBar {
width: 0%;
height: 30px;
background-color: #4CAF50;
text-align: center;
line-height: 30px;
color: white;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
test success |
<div class="testProgress">
<div id="pingTestBar" class="testProgressBar"></div>
</div>
Here's your code modified.
I eliminated the global var widthProgressBarPing by using the width of the barId element that's always there (var widthProgressBar = elem.style.width.slice(0, -4);).
// handles the click event, sends the query
function getSuccessOutput(barId) {
widthProgressBar = 0;
startProgress(barId);
$.ajax({
url: '/echo/js/?js=hello%20world!',
complete: function(response) {
widthProgressBar = 99;
},
error: function() {
widthProgressBar = 99;
},
});
return false;
}
function startProgress(barId) {
var elem = document.getElementById(barId);
var widthProgressBar = elem.style.width.slice(0, -4);
var id = setInterval(frame, 15);
function frame() {
if (widthProgressBar >= 90 && widthProgressBar < 99) {}
if (widthProgressBar >= 100) {
clearInterval(id);
} else {
widthProgressBar++;
elem.style.width = widthProgressBar + '%';
elem.innerHTML = widthProgressBar * 1 + '%';
}
}
}
.testProgress {
width: 100%;
background-color: #ddd;
}
.testProgressBar {
width: 0%;
height: 30px;
background-color: #4CAF50;
text-align: center;
line-height: 30px;
color: white;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
test success ||
<div class="testProgress">
<div id="pingTestBar" class="testProgressBar"></div>
</div>
By passing an argument to startProgress(barId) you can use the same function for different bars.
// handles the click event, sends the query
function getSuccessOutput(barId) {
widthProgressBar = 0;
startProgress(barId);
$.ajax({
url: '/echo/js/?js=hello%20world!',
complete: function(response) {
widthProgressBar = 99;
},
error: function() {
widthProgressBar = 99;
},
});
return false;
}
function startProgress(barId) {
var elem = document.getElementById(barId);
var widthProgressBar = elem.style.width.slice(0, -4);
var id = setInterval(frame, 15);
function frame() {
if (widthProgressBar >= 90 && widthProgressBar < 99) {}
if (widthProgressBar >= 100) {
clearInterval(id);
} else {
widthProgressBar++;
elem.style.width = widthProgressBar + '%';
elem.innerHTML = widthProgressBar * 1 + '%';
}
}
}
.testProgress {
width: 100%;
background-color: #ddd;
}
.testProgressBar {
width: 0%;
height: 30px;
background-color: #4CAF50;
text-align: center;
line-height: 30px;
color: white;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
test success ||
test success2
<div class="testProgress">
<div id="pingTestBar" class="testProgressBar"></div>
</div>
<div class="testProgress">
<div id="pingTestBar2" class="testProgressBar"></div>
</div>
[cut] There are at least three problems in my solution:
I have to reset progress bar 'width' in 3 places
I must have public
variable (widthProgressBar)
I cannot reuse function 'startProgress' in
case I want to have two progress bars at same page.
Simply initialize/reset once when getSuccessOutput() starts
Use the width attribute stored on each bar
Pass the "bar" as arguments, so you can use many bars as you need.
Anyway, you could use .animate() in order to show the progress, so you avoid to keep interval id and the code is more readable.
Please, take a look to following snippet:
function getSuccessOutput() {
//Reset all progress bars
$(".testProgressBar").width(0);
$(".testProgressBar").text("");
//Start requests
doRequest($("#pingTestBar"), 1200);
doRequest($("#pingTestBar2"), 1500);
doRequest($("#pingTestBar3"), 800);
}
function startProgress(bar) {
bar.animate(
{
width:'100%'
},
{
step: function() {
setText(bar);
},
duration: 2000
}
);
}
function complete(bar) {
console.log("Complete " + bar.attr('id'));
bar.finish().animate(
{
width:'100%'
},
{
step: function(){
setText(bar);
}
}
);
}
function setText(bar){
var text = bar.width() / bar.parent().width() * 100;
bar.text(text.toFixed(0));
}
function mockAjax(options) {
var that = {
done: function done(callback) {
if (options.success)
setTimeout(callback, options.timeout, options.response);
return that;
},
error: function error(callback) {
if (!options.success)
setTimeout(callback, options.timeout, options.response);
return that;
}
};
return that;
}
function doRequest(bar, duration){
var mock = {
ajax: function() {
return mockAjax({
success: true,
response: {},
timeout: duration
});
}
};
startProgress(bar);
mock.ajax()
.done(
function (response) {
complete(bar);
}
)
.error(
function (response) {
complete(bar);
}
);
}
.testProgress {
width: 100%;
background-color: #ddd;
}
.testProgressBar {
width: 0%;
height: 30px;
background-color: #4CAF50;
text-align: center;
line-height: 30px;
color: white;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
test success |
<div class="testProgress">
<div id="pingTestBar" class="testProgressBar"></div>
</div>
<div class="testProgress">
<div id="pingTestBar2" class="testProgressBar"></div>
</div>
<div class="testProgress">
<div id="pingTestBar3" class="testProgressBar"></div>
</div>
I hope it helps you, bye.
I am making a simple game that if the characters touch the "obstacle" which is another div the character that touches it will slow down while they are collided.
I already have a code for this, but it is only working for my .obstacle1 div even if I tried using jquery.each or I'm just missing something.
Here is the code which is working only for .obstacle1
HTML
<div class="field">
<div id="char1" class="characters character1">char1</div>
<div id="char2" class="characters character2">char2</div>
<div id="char3" class="characters character3">char3</div>
<div class="obstacles obstacle1">1</div>
<div class="obstacles obstacle2">2</div>
</div>
CSS
* {
padding: 0;
margin: 0;
}
.field-container {
overflow: scroll;
}
.field {
width: 1550px;
height: 700px;
border: 1px solid red;
position: relative;
}
.characters {
position: absolute;
width: 50px;
height: 50px;
transition: .1s ease-in-out;
}
.character1 {
background-color: blue;
top: 100px;
left: 0;
}
.character2 {
background-color: green;
top: 175px;
left: 0;
}
.character3 {
background-color: red;
top: 250px;
left: 0;
}
.obstacle1 {
height: 50px;
width: 50px;
background-color: lightblue;
position: absolute;
top: 200px;
left: 500px;
}
.obstacle2 {
height: 50px;
width: 50px;
background-color: lightblue;
position: absolute;
top: 120px;
left: 750px;
}
jQuery
$(document).ready(function(){
intervalCharacters = setInterval(function(){
moveChar();
},100);
function moveChar() {
$(".characters").each(function(){
move($(this));
});
}
/*--------------
OBSTACLES
---------------*/
var obstacle1 = $(".obstacles");
var obstacle1CurrentPosX = obstacle1.offset().left;
var obstacle1CurrentPosY = obstacle1.offset().top;
var obstacle1Height = obstacle1.outerHeight();
var obstacle1Width = obstacle1.outerWidth();
var totalY = obstacle1CurrentPosY + obstacle1Height;
var totalX = obstacle1CurrentPosX + obstacle1Width;
function checkIfCollidesChar(thisChar) {
var thisCharPosX = thisChar.offset().left;
var thisCharPosY = thisChar.offset().top;
var thisCharWidth = thisChar.outerWidth();
var thisCharHeight = thisChar.outerHeight();
var totalCharY = thisCharPosY + thisCharHeight;
var totalCharX = thisCharPosX + thisCharWidth;
if (totalY < thisCharPosY || obstacle1CurrentPosY > totalCharY || totalX < thisCharPosX || obstacle1CurrentPosX > totalCharX) {
return false;
console.log("FALSE");
} else {
return true
console.log("TRUE");
}
}
/* -----
move the characters
---- */
var moveFromLeft = 0;
var maxPosition = 1500;
function move(thisChar) {
var _this = thisChar;
var currentPosition = _this.offset().left;
var charSpeed = Math.floor(Math.random() * (10 - 0 + 1)) + 0;
if(checkIfCollidesChar(_this)) {
if(_this.offset().left > maxPosition) {
moveFromLeft = maxPosition;
}else{
moveFromLeft = currentPosition + (charSpeed*.25);
}
}else{
if(_this.offset().left > maxPosition) {
moveFromLeft = maxPosition;
}else{
moveFromLeft = currentPosition + charSpeed;
}
}
_this.css({
"left" : moveFromLeft,
});
if(moveFromLeft > maxPosition) {
checkIfFinish(_this);
_this.css({
"left" : maxPosition+"px",
});
}
_this.html(moveFromLeft);
}
});
Here is my fiddle.
Here's a fiddle with my suggested fix:
https://jsfiddle.net/40evn8pr/
The problem is that you're 'flattening' the obstacles jquery selection to a single value when you're directly asking for its offset/width/height. You should ask every element from the jquery selection what its offset is with an '$.each' loop to have every obstacle work.
$(document).ready(function(){
intervalCharacters = setInterval(function(){
moveChar();
},100);
function moveChar() {
$(".characters").each(function(){
move($(this));
});
}
var position = ["first","second","third"];
var counter = 0;
function checkIfFinish(thisChar) {
var position2 = position[counter];
counter++;
$(".result").append("<br>Position"+position2+ " counter" + counter + " : " + thisChar.attr("id"));
if(counter >= 3) {
clearInterval(interval);
}
}
/*--------------
OBSTACLES
---------------*/
var obstacle1 = $(".obstacles");
function checkIfCollidesChar(thisChar) {
var thisCharPosX = thisChar.offset().left;
var thisCharPosY = thisChar.offset().top;
var thisCharWidth = thisChar.outerWidth();
var thisCharHeight = thisChar.outerHeight();
var totalCharY = thisCharPosY + thisCharHeight;
var totalCharX = thisCharPosX + thisCharWidth;
var isCollision = false;
$.each(obstacle1, function(i, ob) {
var obstacle1CurrentPosX = $(ob).offset().left;
var obstacle1CurrentPosY = $(ob).offset().top;
var obstacle1Height = obstacle1.outerHeight();
var obstacle1Width = obstacle1.outerWidth();
var totalY = obstacle1CurrentPosY + obstacle1Height;
var totalX = obstacle1CurrentPosX + obstacle1Width;
if (!(totalY < thisCharPosY || obstacle1CurrentPosY > totalCharY || totalX < thisCharPosX || obstacle1CurrentPosX > totalCharX)) {
isCollision = true;
}
});
return isCollision;
}
/* -----
move the characters
---- */
var moveFromLeft = 0;
var maxPosition = 1500;
function move(thisChar) {
var _this = thisChar;
var currentPosition = _this.offset().left;
var charSpeed = Math.floor(Math.random() * (10 - 0 + 1)) + 0;
if(checkIfCollidesChar(_this)) {
if(_this.offset().left > maxPosition) {
moveFromLeft = maxPosition;
}else{
moveFromLeft = currentPosition + (charSpeed*.25);
}
}else{
if(_this.offset().left > maxPosition) {
moveFromLeft = maxPosition;
}else{
moveFromLeft = currentPosition + charSpeed;
}
}
_this.css({
"left" : moveFromLeft,
});
if(moveFromLeft > maxPosition) {
checkIfFinish(_this);
_this.css({
"left" : maxPosition+"px",
});
}
_this.html(moveFromLeft);
}
});
I think you are almost good. For your loop, you can use as model the
$(".characters").each(function(){
move($(this));
});
In your case, this would give :
$(".obstacles").each(function(){
var obstacle1 = $(this)
var obstacle1CurrentPosX = obstacle1.offset().left;
var obstacle1CurrentPosY = obstacle1.offset().top;
var obstacle1Height = obstacle1.outerHeight();
var obstacle1Width = obstacle1.outerWidth();
var totalY = obstacle1CurrentPosY + obstacle1Height;
var totalX = obstacle1CurrentPosX + obstacle1Width;
...
});
Hey this is my first time on Stackoverflow!
I am building a small javascript html5 game where you click on objects kind of like whack-a-mole.. The goal is to kill as many "gem green" and " gem blue" as possible in 10 seconds, and when you click on the "gem red".. the game ends and plays a sound.
I got most things to work, except I can't find a way to make the game end when clicking on "gem red".. I have tried lots of functions and listeners.. but to no avail.. can anyone help me figure this out?
Here is the code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<title>HTML 5 Gem Game</title>
<meta name="viewport" content="width=device-width, height=device-height, initial-scale=1">
<style>
section#game {
width: 480px;
height: 800px;
max-width: 100%;
max-height: 100%;
overflow: hidden;
position: relative;
background-image: url('img/Splash.png');
position: relative;
color: #ffffff;
font-size: 30px;
font-family: "arial,sans-serif";
}
section#game .score{
display: block;
position: absolute;
top: 10px;
left: 10px;
}
section#game .time{
display: block;
position: absolute;
top: 10px;
right: 10px;
}
section#game .start{
display: block;
padding-top: 40%;
margin: 0 auto 0 auto;
text-align: center;
width: 70%;
cursor: pointer;
}
section#game .start .high-scores{
text-align: left;
}
section#game .gem{
display: block;
position: absolute;
width: 40px;
height: 44px;
cursor: pointer;
}
section#game .gem.green{
background: url('img/Gem Green.png') no-repeat top left;
}
section#game .gem.blue{
background: url('img/Gem Blue.png') no-repeat top left;
}
section#game .gem.red{
background: url('img/Gem Red.png') no-repeat top left;
}
</style>
<script>
function addEvent(element, event, delegate ) {
if (typeof (window.event) != 'undefined' && element.attachEvent)
element.attachEvent('on' + event, delegate);
else
element.addEventListener(event, delegate, false);
}
function Game(){
var game = document.querySelector("section#game");
var score = game.querySelector("section#game span.score");
var high_scores = game.querySelector("section#game ol.high-scores");
var time = game.querySelector("section#game span.time");
var start = game.querySelector("section#game span.start");
function Gem(Class, Value, MaxTTL) {
this.Class = Class;
this.Value = Value;
this.MaxTTL = MaxTTL;
};
var gems = new Array();
gems[0] = new Gem('green', 10, 1.2);
gems[1] = new Gem('blue', 20, 1);
gems[2] = new Gem('red', 50, 0.75);
function Click(event)
{
if(event.preventDefault) event.preventDefault();
if (event.stopPropagation) event.stopPropagation();
else event.cancelBubble = true;
var target = event.target || event.srcElement;
if(target.className.indexOf('gem') > -1){
var value = parseInt(target.getAttribute('data-value'));
var current = parseInt( score.innerHTML );
var audio = new Audio('music/blaster.mp3');
audio.play();
score.innerHTML = current + value;
target.parentNode.removeChild(target);
}
return false;
}
function Remove(id) {
var gem = game.querySelector("#" + id);
if(typeof(gem) != 'undefined')
gem.parentNode.removeChild(gem);
}
function Spawn() {
var index = Math.floor( ( Math.random() * 3 ) );
var gem = gems[index];
var id = Math.floor( ( Math.random() * 1000 ) + 1 );
var ttl = Math.floor( ( Math.random() * parseInt(gem.MaxTTL) * 1000 ) + 1000 ); //between 1s and MaxTTL
var x = Math.floor( ( Math.random() * ( game.offsetWidth - 40 ) ) );
var y = Math.floor( ( Math.random() * ( game.offsetHeight - 44 ) ) );
var fragment = document.createElement('span');
fragment.id = "gem-" + id;
fragment.setAttribute('class', "gem " + gem.Class);
fragment.setAttribute('data-value', gem.Value);
game.appendChild(fragment);
fragment.style.left = x + "px";
fragment.style.top = y + "px";
setTimeout( function(){
Remove(fragment.id);
}, ttl)
}
<!-- parse high score keeper -->
function HighScores() {
if(typeof(Storage)!=="undefined"){
var scores = false;
if(localStorage["high-scores"]) {
high_scores.style.display = "block";
high_scores.innerHTML = '';
scores = JSON.parse(localStorage["high-scores"]);
scores = scores.sort(function(a,b){return parseInt(b)-parseInt(a)});
for(var i = 0; i < 10; i++){
var s = scores[i];
var fragment = document.createElement('li');
fragment.innerHTML = (typeof(s) != "undefined" ? s : "" );
high_scores.appendChild(fragment);
}
}
} else {
high_scores.style.display = "none";
}
}
function UpdateScore() {
if(typeof(Storage)!=="undefined"){
var current = parseInt(score.innerHTML);
var scores = false;
if(localStorage["high-scores"]) {
scores = JSON.parse(localStorage["high-scores"]);
scores = scores.sort(function(a,b){return parseInt(b)-parseInt(a)});
for(var i = 0; i < 10; i++){
var s = parseInt(scores[i]);
var val = (!isNaN(s) ? s : 0 );
if(current > val)
{
val = current;
scores.splice(i, 0, parseInt(current));
break;
}
}
scores.length = 10;
localStorage["high-scores"] = JSON.stringify(scores);
} else {
var scores = new Array();
scores[0] = current;
localStorage["high-scores"] = JSON.stringify(scores);
}
HighScores();
}
}
function Stop(interval) {
clearInterval(interval);
}
this.Start = function() {
score.innerHTML = "0";
start.style.display = "none";
var interval = setInterval(Spawn, 750);
var count = 10;
var counter = null;
function timer()
{
count = count-1;
if (count <= 0)
{
var left = document.querySelectorAll("section#game .gem");
for (var i = 0; i < left.length; i++) {
if(left[i] && left[i].parentNode) {
left[i].parentNode.removeChild(left[i]);
}
}
Stop(interval);
Stop(counter);
time.innerHTML = "Game Over!";
start.style.display = "block";
UpdateScore();
return;
} else {
time.innerHTML = count + "s left";
}
}
counter = setInterval(timer, 1000);
setTimeout( function(){
Stop(interval);
}, count * 1000)
};
addEvent(game, 'click', Click);
addEvent(start, 'click', this.Start);
HighScores();
}
addEvent(document, 'readystatechange', function() {
if ( document.readyState !== "complete" )
return true;
var game = new Game();
});
</script>
</head>
<body>
<div id="page">
<section id="game">
<span class="score">0</span>
<span class="time">0</span>
<span class="start">START!
<ol class="high-scores"></ol>
</span>
</section>
</div>
</body>
</html>
Alessio -
You only need a few minor changes to your code to make it work. The example below should help you get started in the right direction. Good luck.
Changes:
Add an endGame() function and move the stop game logic from the timer() function into it.
Add a line to the click() function to check for red gem clicks.
if (target.className.indexOf('red') > 0) endGame("Red Gem - You win!");
Declare the count, counter, and interval variables at the top of your Game object.
The code below also has a few minor CSS changes used for debugging which you can remove.
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<title>HTML 5 Gem Game</title>
<meta name="viewport" content="width=device-width, height=device-height, initial-scale=1">
<style>
section#game {
width: 480px;
height: 800px;
max-width: 100%;
max-height: 100%;
overflow: hidden;
position: relative;
background-image: url('img/Splash.png');
border: 1px red dotted;
position: relative;
color: red;
font-size: 30px;
font-family: "arial,sans-serif";
}
section#game .score{
display: block;
position: absolute;
top: 10px;
left: 10px;
}
section#game .time{
display: block;
position: absolute;
top: 10px;
right: 10px;
}
section#game .start{
display: block;
padding-top: 40%;
margin: 0 auto 0 auto;
text-align: center;
width: 70%;
cursor: pointer;
}
section#game .start .high-scores{
text-align: left;
}
section#game .gem{
display: block;
position: absolute;
width: 40px;
height: 44px;
cursor: pointer;
}
section#game .gem.green{
background: url('img/Gem Green.png') no-repeat top left;
background-color: green;
}
section#game .gem.blue{
background: url('img/Gem Blue.png') no-repeat top left;
background-color: blue;
}
section#game .gem.red{
background: url('img/Gem Red.png') no-repeat top left;
background-color: red;
}
</style>
<script>
function addEvent(element, event, delegate ) {
if (typeof (window.event) != 'undefined' && element.attachEvent)
element.attachEvent('on' + event, delegate);
else
element.addEventListener(event, delegate, false);
}
function Game(){
var game = document.querySelector("section#game");
var score = game.querySelector("section#game span.score");
var high_scores = game.querySelector("section#game ol.high-scores");
var time = game.querySelector("section#game span.time");
var start = game.querySelector("section#game span.start");
var interval, counter, count;
function Gem(Class, Value, MaxTTL) {
this.Class = Class;
this.Value = Value;
this.MaxTTL = MaxTTL;
};
var gems = new Array();
gems[0] = new Gem('green', 10, 1.2);
gems[1] = new Gem('blue', 20, 1);
gems[2] = new Gem('red', 50, 0.75);
function Click(event)
{
if(event.preventDefault) event.preventDefault();
if (event.stopPropagation) event.stopPropagation();
else event.cancelBubble = true;
var target = event.target || event.srcElement;
if(target.className.indexOf('gem') > -1){
var value = parseInt(target.getAttribute('data-value'));
var current = parseInt( score.innerHTML );
var audio = new Audio('music/blaster.mp3');
audio.play();
score.innerHTML = current + value;
target.parentNode.removeChild(target);
if (target.className.indexOf('red') > 0) endGame("Red Gem - You win!");
}
return false;
}
function Remove(id) {
var gem = game.querySelector("#" + id);
if(typeof(gem) != 'undefined')
gem.parentNode.removeChild(gem);
}
function Spawn() {
var index = Math.floor( ( Math.random() * 3 ) );
var gem = gems[index];
var id = Math.floor( ( Math.random() * 1000 ) + 1 );
var ttl = Math.floor( ( Math.random() * parseInt(gem.MaxTTL) * 1000 ) + 1000 ); //between 1s and MaxTTL
var x = Math.floor( ( Math.random() * ( game.offsetWidth - 40 ) ) );
var y = Math.floor( ( Math.random() * ( game.offsetHeight - 44 ) ) );
var fragment = document.createElement('span');
fragment.id = "gem-" + id;
fragment.setAttribute('class', "gem " + gem.Class);
fragment.setAttribute('data-value', gem.Value);
game.appendChild(fragment);
fragment.style.left = x + "px";
fragment.style.top = y + "px";
setTimeout( function(){
Remove(fragment.id);
}, ttl)
}
<!-- parse high score keeper -->
function HighScores() {
if(typeof(Storage)!=="undefined"){
var scores = false;
if(localStorage["high-scores"]) {
high_scores.style.display = "block";
high_scores.innerHTML = '';
scores = JSON.parse(localStorage["high-scores"]);
scores = scores.sort(function(a,b){return parseInt(b)-parseInt(a)});
for(var i = 0; i < 10; i++){
var s = scores[i];
var fragment = document.createElement('li');
fragment.innerHTML = (typeof(s) != "undefined" ? s : "" );
high_scores.appendChild(fragment);
}
}
} else {
high_scores.style.display = "none";
}
}
function UpdateScore() {
if(typeof(Storage)!=="undefined"){
var current = parseInt(score.innerHTML);
var scores = false;
if(localStorage["high-scores"]) {
scores = JSON.parse(localStorage["high-scores"]);
scores = scores.sort(function(a,b){return parseInt(b)-parseInt(a)});
for(var i = 0; i < 10; i++){
var s = parseInt(scores[i]);
var val = (!isNaN(s) ? s : 0 );
if(current > val)
{
val = current;
scores.splice(i, 0, parseInt(current));
break;
}
}
scores.length = 10;
localStorage["high-scores"] = JSON.stringify(scores);
} else {
var scores = new Array();
scores[0] = current;
localStorage["high-scores"] = JSON.stringify(scores);
}
HighScores();
}
}
function Stop(interval) {
clearInterval(interval);
}
function endGame( msg ) {
count = 0;
Stop(interval);
Stop(counter);
var left = document.querySelectorAll("section#game .gem");
for (var i = 0; i < left.length; i++) {
if(left[i] && left[i].parentNode) {
left[i].parentNode.removeChild(left[i]);
}
}
time.innerHTML = msg || "Game Over!";
start.style.display = "block";
UpdateScore();
}
this.Start = function() {
score.innerHTML = "0";
start.style.display = "none";
interval = setInterval(Spawn, 750);
count = 10;
counter = null;
function timer()
{
count = count-1;
if (count <= 0)
{
endGame();
return;
} else {
time.innerHTML = count + "s left";
}
}
counter = setInterval(timer, 1000);
setTimeout( function(){
Stop(interval);
}, count * 1000)
};
addEvent(game, 'click', Click);
addEvent(start, 'click', this.Start);
HighScores();
}
addEvent(document, 'readystatechange', function() {
if ( document.readyState !== "complete" )
return true;
var game = new Game();
});
</script>
</head>
<body>
<div id="page">
<section id="game">
<span class="score">0</span>
<span class="time">0</span>
<span class="start">START!
<ol class="high-scores"></ol>
</span>
</section>
</div>
</body>
</html>
For starters, you shouldn't include a style sheet and your entire HTML file since neither is relevant and you should use a canvas element instead of this chaotic use of CSS and html elements, which would allow the size of your code to be halved. Furthermore, you should be able to fix this by just changing some global boolean variable to false when the red gem is clicked and when the boolean variable is false (this if statement belongs at the end of your game loop) you call Stop(arg)/clearInterval(arg). Given that your current code doesn't seem to have a global boolean variable indicating game state (using an enumeration would generally be a cleaner solution but a simple boolean seems to suit this case)