js popup window to play .flv flash video using jwplayer.swf - javascript

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.

Related

How to add bg image to API weather project?

Hello lately i've been working with APIs to get the hang of them through the usual weather app project BUT i'm pretty much still a beginner in javascript and i was wondering how to add a background image that matches the weather report of the city selected by the user.
I wanted to create many classes in css, each called like the weather (ex: .clear, .clouds,.rain etc...) and then use a classList.add() method to change it each time depending on the openWeatherMap data. I tried adding something like document.getElementsByTagName("body")[0].classList.add(weatherValue); inside the .then promise but it doesn't work. Can somebody help me? If there's a much simpler way i'd like to hear about it too :) Thank you so much
var button = document.querySelector(".button");
var inputValue = document.querySelector(".inputValue");
var cityName = document.querySelector(".name");
var weather = document.querySelector(".weather");
var desc = document.querySelector(".desc");
var temp = document.querySelector(".temp");
var humi = document.querySelector(".humi");
button.addEventListener("click", function() {
fetch("https://api.openweathermap.org/data/2.5/weather?q="+inputValue.value+"&appid={myapikey}")
.then(response => response.json())
.then(data => {
var nameValue = data['name'];
var weatherValue = data['weather'][0]['main'];
var tempValue = data['main']['temp'];
var descValue = data['weather'][0]['description'];
var humiValue = data['main']['humidity'];
cityName.innerHTML = nameValue;
weather.innerHTML = weatherValue; // this gives "clear" "clouds" etc to <p> element
desc.innerHTML = descValue;
temp.innerHTML = "Temperature: " + tempValue;
humi.innerHTML = "Humidity: " + humiValue;
})
.catch(err => alert("Wrong city name!"))
})
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: "Nunito", sans-serif;
background-repeat: no-repeat;
background-size: cover;
}
.input {
text-align: center;
margin: 100px 0;
}
input[type="text"] {
height: 50px;
width: 600px;
background: #e7e7e7;
font-family: "Nunito", sans-serif;
font-weight: bold;
font-size: 20px;
border: none;
border-radius: 2px;
padding: 10px 10px;
}
input[type="submit"] {
height: 50px;
width: 100px;
background: #e7e7e7;
font-family: "Nunito", sans-serif;
font-weight: bold;
font-size: 20px;
border: none;
border-radius: 2px;
}
.display {
text-align: center;
}
.clear {
/* background image here */
}
.clouds {
/* another background image here */
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="weather_app.css">
</head>
<body>
<div class="input">
<input type="text" class="inputValue" placeholder="Enter a city">
<input type="submit" value="Submit" class="button">
</div>
<div class="display">
<h1 class="name"></h1>
<p class="weather"></p>
<p class="desc"></p>
<p class="temp"></p>
<p class="humi"></p>
</div>
<script src= "weather_app.js"></script>
</body>
</html>
I did a project like this not long ago, https://github.com/Kroplewski-M/Weather-App , I used the openWeater API. I did this:
function setBackground(weather) {
if (weather == "Rain") {
background.src = "./resources/rainy-weather.jpg";
} else if (weather == "Snow") {
background.src = "./resources/snowy-weather.jpg";
} else if (weather == "Clear") {
background.src = "./resources/sunny-weather.jpg";
} else if (weather == "Clouds") {
background.src = "./resources/cloudy-weather.jpg";
}
}
The openWeather API returns what condition the weather is so you can just if statement on what the condition is and set the background accordingly

JavaScript change image on keypress

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.

Get value from Javascript to Input type Hidden

I am just trying to add code in this javascript to get values of slide to input type="hidden", but i can't get value into input type="hidden", what do I do wrong? Anyway, thanks for your help!
This is javascript code:
// <![CDATA[
var hWidth, bWidth;
function setBgPos(v) {
var off = v * hWidth;
var pos = -bWidth + (v * bWidth);
$('slider').setStyle({backgroundPosition: Math.round(pos - off) + 'px'});
}
function setSlideOutput(v) {
$('percent').innerHTML = Math.round(v * 100) + '%';
}
Event.observe(window, 'load', function() {
hWidth = $('slider-handle').getWidth();
bWidth = $('slider-bar').getWidth();
var slide = new Control.Slider('slider-handle', 'slider-bar', {
sliderValue: 0.25,
onSlide:
function(v) {
setBgPos(v);
setSlideOutput(v);
$('percentage').value = Math.round(v * 100) + '%';
},
onChange:
function(v) {
setBgPos(v);
setSlideOutput(v);
$('percentage').value = Math.round(v * 100) + '%';
}
});
setBgPos(slide.value);
setSlideOutput(slide.value);
});
// ]]>
Html:
<!DOCTYPE html>
<html lang="nl">
<head>
<script src="//ajax.googleapis.com/ajax/libs/prototype/1.7.1.0/prototype.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/scriptaculous/1.9.0/scriptaculous.js"></script>
<style>
#slider, #slider-bar, #slider-handle {
border: 0;
padding: 0;
margin: 0;
}
#slider {
width: 300px;
height:42px;
background: url(img/bg.gif) no-repeat -300px;
margin-left: 42px;
}
#slider-bar {
width:300px;
height:42px;
background: url(img/track.png) no-repeat;
}
#slider-handle {
width:42px;
height:42px;
cursor:move;
background: url(img/gripper.png) no-repeat;
}
#percent {
font-size: 75%;
font-family: arial;
font-weight: bold;
text-align: center;
padding-top: 1.1em;
}
</style>
</head>
<body>
<div id="slider">
<div id="slider-bar">
<div id="slider-handle"><p id="percent"></p></div>
</div>
</div>
<input type="hidden" id="percentage" name="percentage" value="0" />
</body>
</html>
Try using $('#percentage')[0].value
What you need is DOM element, not jquery object.
Or, alternatively, use $('#percentage').val('')
you should use $('#percentage') instead of $('percentage')
UPDATE: Solved to add setvalue, this did help me: http://www.ruby-forum.com/topic/143329 . Thanks for all the tips guys and more thanks for Geek Num 88!

Animated image (e.g. non-GIF) with JavaScript and CSS?

I had been trying to animate a .png file with JavaScript while following this method. This is the .png file that I want to animate. I want the animated logo to be right by "Cupquake," but the logo doesn't even show up, let alone animate. However, changing "span class=logoCquake" in HTML to a div class displays the logo, but it is below the text.
My JavaScript file:
var scrollUp = (function () {
var timerId;
return function (height, times, element) {
var i = 0;
timerId = setInterval(function () {
if (i > times)
i = 0;
element.style.backgroundPosition = "0px -" + i * height + 'px';
i++;
}, 100);
};
})();
scrollUp(130, 30, document.getElementByClass('logoCquake'))
My HTML:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<link rel="stylesheet" href="../css/normalize.css" />
<link rel="stylesheet" href="../css/style.css" />
<script src="../scripts/logoCquake.js" type="text/javascript"></script>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Cupquake - Home</title>
</head>
<body>
<div class="wrapper">
<div class="header">
<div class="topbar">
<div class="mCquake">
</div>
</div>
<br>
<br>
<br>
<span class="ninja">Ninja</span><span class="cupquake">Cupquake</span><span class="logoCquake"></span>
</div>
</div>
</body>
</html>
CSS file:
#font-face
{
font-family: typo_semib;
src: url('fonts/typo_semib.ttf');
}
#font-face
{
font-family: typo_light;
src: url('fonts/typo_light.ttf');
}
.wrapper .header
{
height: 250px;
width: 100%;
background: -webkit-gradient(linear,left top,left bottom,color-stop(0%,#ffa200), color-stop(100%,#d25400));
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffa200',endColorstr='#d25400',GradientType=0);
background: -moz-linear-gradient(top,#ffa200,#d25400);
background-image: -o-linear-gradient(#ffa200,#d25400);
overflow: hidden;
}
.wrapper .header .topbar
{
height: 60px;
background-image: url(../imgz/head/hBarSBg.png);
background-repeat: repeat-x;
}
.wrapper .header .topbar .mCquake
{
height: 37px;
width: 278px;
background-image: url(../imgz/head/mCqRight.png);
background-repeat: no-repeat;
float: none;
float: right !important;
margin-right: 10px;
margin-top: 11.5px;
margin-bottom: 11.5px;
}
.wrapper .header .ninja
{
font-family: typo_semib;
font-size: 48px;
color: #303030;
margin-left: 55px;
}
.wrapper .header .cupquake
{
font-family: typo_light;
font-size: 48px;
color: #303030;
}
.wrapper .header .logoCquake
{
height: 112px;
width: 130px;
background-image: url(../imgz/logo/logoCquake.png);
background-repeat: no-repeat;
}
EDIT:
Tried again, but with the second method listed here, still nothing. These are my current HTML and JS codes:
JS:
function SpriteAnim (options) {
var timerId,
i = 0,
element = document.getElementByClass(options.elementClass);
element.style.width = options.width + "px";
element.style.height = options.height + "px";
element.style.backgroundRepeat = "no-repeat";
element.style.backgroundImage = "url(" + options.sprite + ")";
timerId = setInterval(function () {
if (i >= options.frames) {
i = 0;
}
element.style.backgroundPosition = "0px -" + i * options.height + "px";
i ++;
}, 100);
this.stopAnimation = function () {
clearInterval(timerId);
};
}
var cupcake = new SpriteAnim({
width: 130,
height: 112,
frames: 30,
sprite: "..\imgz\logo\logoCquake.png",
elementClass : "logoCquake"
});
HTML:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<link rel="stylesheet" href="../css/normalize.css" />
<link rel="stylesheet" href="../css/style.css" />
<script language="javascript" src="SpriteAnim.js">
</script>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Cupquake - Home</title>
</head>
<body>
<div class="header">
<div class="topbar">
<div class="mCquake">
</div>
</div>
<span class="ninja">Ninja </span><span class="cupquake">Cupquake</span><span class="logoCquake"></span>
</div>
</div>
</body>
</html>
my code seems to work:
<!doctype html>
<style>
div{background:url(http://i1243.photobucket.com/albums/gg555/Nyanja/logoCquake.png);height:33px;width:39px}
</style>
<div id=anim></div>
<script>
var i=0;
setInterval(function(){i+=33.6;document.getElementById("anim").style.backgroundPosition="0px "+i+"px"},100)
</script>
I believe 'span' tag being an inline element it either needs a 'display: block' property or 'float: left', i tried your code and it worked for me after i added 'display: block' to the 'span' tag with class 'logoCquake'. Hope this helps you.
Note: if you use 'display: block' the span will move to new line and if you use 'float: left' the 'span' tag will move to the left of the text.

Position elements on screen using Javascript

I am attempting to use Javascript to position some of my elements on the screen/window. I am doing this to make sure that what ever the dimensions of the users screen, my elements will always be in the centre.
I know that padding & margin can also achieve this, but I am using a custom movement script called raphael.js, & in order to move my elements I need to set out my elements absolutely (its a custom home page, where you click blocks(that are links) & they fly off the screen).
My javascript function to move my elements fails to move my elements. Any suggestions on how to position my elements using javascript would be really helpful.
<!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>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript" src="dropDownMenu.js"></script>
<title></title>
<script src="javascript/raphael.js"></script> <!-- I am using a custom drawing/moving script which is why I cant put the img(id=bkImg) inside the div element -->
<script LANGUAGE="JavaScript" type = "text/javascript">
<!--
function getScreenSize()
{
var res = {"width": 630, "height": 460};
if (document.body)
{
if (document.body.offsetWidth) res["width"] = document.body.offsetWidth;
if (document.body.offsetHeight) res["height"] = document.body.offsetHeight;
}
if (window.innerWidth) res["width"] = window.innerWidth;
if (window.innerHeight) res["height"] = window.innerHeight;
alert( res["width"] );
alert( res["height"] );
return res;
}
function positionBlocksAccordingToScreenSize()
{
// The problem is that the blocks position does not change but they should?
var scrDim = getScreenSize();
var BK_WIDTH = 800;
var BK_HEIGHT = 600;
var X_OFFSET = (scrDim["width"]-BK_WIDTH) / 2; // variable that changes according to the width of the screen
var BLOCK_POS_X = [160, 80, 280, 20, 200, 400];
var BLOCK_POS_Y = [26, 203, 203, 380, 380, 380];
for ( var i=1; i<=5; i++ )
{
//document.getElementById("block"+i).setAttribute( "offsetLeft", X_OFFSET + BLOCK_POS_X[i] ); // doesn't work
//document.getElementById("block"+i).setAttribute( "offsetTop", BLOCK_POS_Y[i] ); // doesn't work
document.getElementById("block"+i).style.left = X_OFFSET + BLOCK_POS_X[i]; // doesn't work
document.getElementById("block"+i).style.top = BLOCK_POS_Y[i]; // doesn't work
}
}
-->
</script>
<style type="text/css" media="all">
<!--
#import url("styles.css");
#blockMenu { z-index: -5; padding: 0; position: absolute; width: 800px;
height: 600px; /*background-image: url("images/menuBk.png");*/ }
#bkImg { z-index: -5; position: relative; }
#block1 { z-index: 60; position: absolute; top: 26px; left: 160px; margin: 0; padding: 0; }
#block2 { z-index: 50; position: absolute; top: 203px; left: 80px; margin: 0; padding: 0; }
#block3 { z-index: 40; position: absolute; top: 203px; left: 280px; margin: 0; padding: 0; }
#block4 { z-index: 30; position: absolute; top: 380px; left: 20px; margin: 0; padding: 0; }
#block5 { z-index: 20; position: absolute; top: 380px; left: 200px; margin: 0; padding: 0; }
#block6 { z-index: 10; position: absolute; top: 380px; left: 400px; margin: 0; padding: 0; }
-->
</style>
</head>
<body onload="positionBlocksAccordingToScreenSize()" style="margin-top: 10%; text-align: center; margin-bottom: 10%; position: relative;">
<img id="bkImg" src="images/menuBk.png" width="800px;" height="600px" alt=""/>
<!-- The above image should be displayed behind the below div. I am using the raphael.js movement script, so I cannot place
this image inside the div, because it will get erased when I call raphael.clear(); -->
<div id="blockMenu">
<div id="block1"><img src="images/block1.png" width="200" height="200"/></div>
<div id="block2"><img src="images/block2.png" width="200" height="200"/></div>
<div id="block3"><img src="images/block3.png" width="200" height="200"/></div>
<div id="block4"><img src="images/block4.png" width="200" height="200"/></div>
<div id="block5"><img src="images/block5.png" width="200" height="200"/></div>
<div id="block6"><img src="images/block6.png" width="200" height="200"/></div>
</div>
</body>
</html>
You're not setting the left and top properties correctly, you need to add the unit e.g 'px' for pixels.
document.getElementById("block"+i).style.left = X_OFFSET + BLOCK_POS_X[i] + 'px';
document.getElementById("block"+i).style.top = BLOCK_POS_Y[i] + 'px';
"Would you be able to suggest a line of jQuery code that could place my elements correctly?"
The following code uses jQuery and will center an absolutely positioned element on load and on window resize.
http://jsfiddle.net/Fu3L6/
HTML...
<div id="element">Test</div>
CSS...
#element {
position: absolute;
background-color: red;
width: 200px;
}
jQuery...
$(document).ready(function () {
centerInViewport('#element');
$(window).resize(function () {
centerInViewport('#element');
});
});
function centerInViewport(e) {
$docWidth = $(document).width();
$elWidth = $(e).width();
$offset = ($docWidth - $elWidth) / 2;
$(e).css("marginLeft", $offset + "px");
}

Categories

Resources