I am looking for the correct Javascript only (not JQuery) code that will change a div width from 100% to 1000px if the width of the browser is < 1000px. The code will change back to 100% if the browser size is >1000px. I am determined to learn JavaScript before I learn JQuery! I can find load of JQuery solutions but want to learn JS! In the fiddle I want to change the div element named "red". The reason is because min-width: 1000px; is not supported in ie and I therefore want a working solution. Thank you very much for any help.
Link to fiddle is here: http://jsfiddle.net/Margate/ddENL/
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<title>Positioning</title>
<style type="text/css">
#red {position: absolute; margin-top: 100px; width: 100%; min-width: 1000px; height: 400px; background-color: red;}
#contents {position: relative; top: 10px; width: 1000px; height: 600px; margin: 0px auto; border: 1px solid white;}
html, body, div {margin: 0; padding: 0; border: 0;}
</style>
</head>
<body style="background-color: black;">
<div id="red"></div>
<div id="contents"></div>
</body>
</html>
JavaScript:
window.onresize = function() {
var widthViewport = window.innerWidth || document.body.clientWidth;
var el = document.getElementById('red');
if( widthViewport < 1000 ) {
// Append the classname which specifies the fixed width
el.className += ' fixed_width';
} else {
// Remove the classname that fixes the width at 1000px
el.className = el.className.replace( /(\b\s*fixed_width\b)+/, '' );
}
};
CSS:
.fixed_width{
width: 1000px;
}
Try this
window.onload = function() {
var browserWidth = document.body.clientWidth;
if(browserWidth < 1000) {
document.getElementById('red').style.width = '1000px';
}
};
var ObjRedDiv=document.getElementById('red');
/** Get Width Of the browser **/
var browserWidth=window.innerWidth || document.body.clientWidth;
if(browserWidth<1000)
{
ObjRedDiv.style.width='1000px';
}
else
{
ObjRedDiv.style.width='100%';
}
For old ie , you can use javascript in header, extern file or with expression in css.
It allows then to insert javascript inside CSS file that only IE understands.
base line for this would be:
= document.body.clientWidth < 1001 ? "100px" : "auto"
In CSS file
width: expression( document.body.clientWidth < 1001 ? "100px" : "auto" ); /* set min-width for IE */
Something like this: http://jsfiddle.net/ddENL/1/ ?
detectResize();
window.onresize = detectResize;
function detectResize(){
var redElement = document.getElementById("red");
var windowWidth = window.innerWidth;
if (windowWidth < 1000){
redElement.innerHTML = "Less than 1000";
} else {
redElement.innerHTML = "More than 1000";
}
}
Related
I am beginner to JS and I am trying to create a simple game in it. I am looking for a way to stop the player (20px x 20px) box causing the screen to scroll, i am looking for a fixed screen where the player cannot exceed the sides of the screen. Please see previous attempts below.
HTML :
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
<link rel="stylesheet" href="Style.css">
</head>
<body>
<div id="player"></div>
<script type="text/javascript" src="Script.js"></script>
</body>
</html>
CSS:
body{
margin: 0;
padding: 0;
background-color: red;
}
#player{
border-radius: 30%;
padding: 0px;
margin: 0px;
background-color: white;
width: 20px;
height: 20px;
position: absolute;
}
JavaScript:
var player = document.getElementById("player")
var pros = {'top': 0, 'left': 0, 'speed': 10}
var ws = {'h': screen.height, 'w': screen.width}
document.addEventListener("keydown", function(event){
var keyP = event.key;
if(keyP === "ArrowDown"){
pros.top = pros.top + pros.speed;
}else if(keyP === "ArrowUp"){
pros.top = pros.top - pros.speed;
}else if(keyP === "ArrowLeft"){
pros.left = pros.left - pros.speed;
}else if(keyP === "ArrowRight"){
pros.left = pros.left + pros.speed;
}
if(pros.top < 0){
pros.top = 0;
}else if(pros.top > ws.h){
pros.top = ws.h;
}else if(pros.left < 0){
pros.left = 0;
}else if(pros.left > ws.w){
pros.left = ws.w;
}
player.style.top = `${pros.top}px`;
player.style.left = `${pros.left}px`;
});
Now, I want the element to never escape the given screen area. As you can see in the code that I have tried to use screen.height/screen.width to control it but still it escapes the area and the scroll bars get activated even in the full screen mode. It looks too messy for a game.
Here is picture of how it escapes the area:
In Full Screen Mode :
Without Full Screen Mode :
The most accurate position and dimensions measurements are available via the getBoundingClientRect() function.
So at the top of your keystroke callback I'd add two lines:
var screenRect = document.body.getBoundingClientRect();
var playerRect = player.getBoundingClientRect();
These need to be calculated at every iteration in order to make sure that the "game" adapts to every screen change. Also any position increments are better calculated in percents of the screen size rather than static pixel values.
Your screen edge check should be rewritten like this:
if(playerRect.top < 0){
pros.top = 0;
} else if(playerRect.top + playerRect.height > screenRect.height){
// make sure the bottom edge of the player doesn't go over the bottom edge of the screen
pros.top = screenRect.height - playerRect.height;
}
if(playerRect.left < 0){
pros.left = 0;
} else if(playerRect.left + playerRect.width + > screenRect.width){
// make sure the right edge of the player doesn't go over the right edge of the screen
pros.left = screenRect.width - playerRect.width;
}
On the CSS side, try the following:
body{
margin: 0;
padding: 0;
background-color: red;
width: 100vw;
height: 100vh;
overflow: hidden;
}
#player{
border-radius: 30%;
padding: 0px;
margin: 0px;
background-color: white;
width: 20px;
height: 20px;
position: fixed;
}
The height and width of your PLAYER object is 20px as concluded from the Stylesheet that you have provided.
If you place your element on a 2D plane, then it's coordinates will be the point where its TOP-LEFT corner lie. Focus here.
So, your JavaScript should change to this:
...
if(pros.top < 0){
pros.top = 0;
}else if(pros.top > ws.h-20){ // changed here
pros.top = ws.h-20; // try playing with the value here
}else if(pros.left < 0){
pros.left = 0;
}else if(pros.left > ws.w-20){ //changed here
pros.left = ws.w-20; // try playing with the value here
}
...
This would always place the #player element 20px inside on the horizntal axis and 20px on the vertical axis. I was successful in limiting the appearance of the horizontal scroll-bar but the vertical vanished only for a value of ws.h-40.
Hope this helps.
Hey :) Maybe this helps you:
<style type="text/css">
body {
overflow:hidden;
}
</style>
Setting the overflow: hidden will hide the scrollbar.
I'm pretty new at coding, and right now I'm working on a small school assignment where the idea is to create a single serving site.
I want to make a face from the side with a nose that grows - from left to right - (exactly like Pinocchio) when scrolling the page.
Maybe the code I have written will help to explain what I want to do more accurately...
My question is: what should I do to have my nose element fixed centered to the left, and growing more and more to the right when scrolling? When I set the position to fixed my nose element disappears.
This is my source of inspiration/code -> http://jsfiddle.net/95EtZ/11/
Here is my code:
$(function() {
var Node = $('#container'),
BaseWidth = Node.width();
$(window).resize(function() {
$('#container').css({
top: ($(window).height() - $('#container').outerHeight()) / 2
});
});
$(window).resize();
var $scrollingDiv = Node;
$(window).scroll(function() {
var winScrollTop = $(window).scrollTop() + 0,
zeroSizeHeight = $(document).height() - $(window).height(),
newSize = BaseWidth * (1 - (winScrollTop / zeroSizeHeight) * (2 / 3));
Node.css({
width: newSize,
"marginTop": winScrollTop + "px"
});
});
});
#added {
background: white;
height: 1500px;
overflow: hidden;
position: relative;
}
#container {
width: 600px;
height: 100px;
background-color: #567;
margin: 0 auto;
position: relative;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="main.css">
</head>
<body>
<div id="added">
<div id="container"></div>
</div>
</body>
</html>
Just make the div floating left and it should work.
#container {
width: 600px;
height: 2000px;
background-color: #567;
margin: 0 auto;
position:relative;
float:left;
}
I have a div with margin auto, in the center (horizontal).
I want to check with jQuery if the div has margin auto.
I tried to get the margin-left with .css(). Mozilla Firefox shows 0px, and Chrome shows a number of pixels... So with this method I cannot check if the div has margin auto...
What I've tried:
$( document ).ready(function() {
$("#the_margin").append( $("#example").css("margin-left") );
});
// Check with Chrome and Firefox...
// Firefox returns 0px, but Chrome returns a number of pixels
#example {
margin: 0 auto 0;
width: 300px;
border: 1px solid #CCC;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="example">
Some Content
</div>
<div id="the_margin" style="font-weight: bold;">
The left margin is:
</div>
What can I do?
Thanks a lot!
EDIT
More clear: HOW CAN I CHECK IF DIV HAS MARGIN AUTO IN JQUERY?
Created a function which reads the css and check the specified id if has margin with auto.
JS (JQuery)
function check_center( the_id ) {
var result = "";
var sheets = document.styleSheets;
var attribute_style = $(the_id).attr( "style" );
if(attribute_style.match(/margin:([a-z0-9- ]+?)auto/) || attribute_style.match(/margin:auto/) || (attribute_style.match(/margin-left:auto/) && attribute_style.match(/margin-right:auto/)) || (attribute_style.match(/margin-left: auto/) && attribute_style.match(/margin-right: auto/)) ) {
result = "true";
} else {
the_id.matches = the_id.matches || the_id.webkitMatchesSelector || the_id.mozMatchesSelector || the_id.msMatchesSelector || the_id.oMatchesSelector;
for (var i in sheets) {
var rules = sheets[i].rules || sheets[i].cssRules;
for (var r in rules) {
if (the_id.matches(rules[r].selectorText)) {
if(result != "true") {
if(rules[r].cssText.match(/margin:([a-z0-9- ]+?)auto/) || rules[r].cssText.match(/margin:auto/) || (rules[r].cssText.match(/margin-left:auto/) && rules[r].cssText.match(/margin-right:auto/)) || (rules[r].cssText.match(/margin-left: auto/) && rules[r].cssText.match(/margin-right: auto/)) ) {
result = "true";
} else {
result = "false";
}
}
}
}
}
}
if(result == "") {
result = "false";
}
return result;
}
$( document ).ready(function() {
$("#the_margin").append( check_center(document.getElementById('example')) );
});
HTML
<div id="example" style="width: 300px;">
Some Content
</div>
<div id="the_margin" style="font-weight: bold;">
The div is centered?
</div>
CSS
#example {
margin: 0 auto 0;
border: 1px solid #CCC;
}
Fiddle http://jsfiddle.net/vn6ajt6r/6/
It works for:
External style sheet
Internal style sheet
Inline style
I think your problem Mozilla Firefox shows 0px, and Chrome shows a number of pixels can be fixed this way :-
#example {
-webkit-margin: 0 auto 0;
-moz-margin: 0 auto 0;
width: 300px;
border: 1px solid #CCC;
}
FIDDLE:
You need to specify the browser while setting margin css
i think the other way can be calculated.
only top example for calculated margin-left value:
$('#example').offset().left - $('#example').position().left
$(document).ready(function() {
$("#the_margin").append(
$('#example').offset().left - $('#example').position().left
);
});
#example {
margin-top: 0;
margin-left: auto;
margin-right: auto;
margin-bottom: 0;
position: relative;
width: 300px;
border: 1px solid #CCC;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="example">
Some Content
</div>
<div id="the_margin" style="font-weight: bold;">
The left margin is:
</div>
I have posted my problem at http://jsfiddle.net/ugnf4/ as it would be make it easier.
Below is my html / javascript code
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<div id="mainContainer">
<div id="pageContainer" style="background: #cdcdcd;"></div>
</div>
<style>
BODY {
margin: 0px;
padding: 0px;
}
#pageContainer {
position: relative;
margin: 10px auto;
-webkit-transform-origin:50% 20%;
-webkit-transform:scale(1.37);
width: 1218px;
height: 774px;
border: 1px solid #000000;
}
#mainContainer {
width: 100%;
overflow: hidden;
}
</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
</script>
<script type="text/javascript">
$(document).ready(function() {
setHeight();
$(window).resize(setHeight);
});
function setHeight()
{
$('#mainContainer').css({'height': $(window).height()});
}
$('#mainContainer').mousemove(function (e) {
});
</script>
</body>
</html>
Currently #mainContainer div has overflow hidden as i dont want to show scroll bars and #pageContainer div (inner div) is scaled at 1.37 using css3, as in certain cases based on screen / browser width height #pageContainer's content would be hidden because of overflow hidden.
I want to code javascript so that if somebody moves cursor in #mainContainer, based on position of mouse X and Y co-ordinates I would like to move #pageContainer so that similar position of #pageContainer would be visible (I hope it is clear).
I m having problem as I m using -webkit-transform-origin, unable to understand how to move #pageContainer around with respect to mouse co-ordinates of #mainContainer.
UPDATE:
I m looking something like what happens in issuu.com website when you open an ebook and zoom it more than the browser size (Should make it more clear)
I m looking for algo or pointer how to achieve it (how to calculate it) not necessarily a working script.
How can this be achieved.
Below is working html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<div id="mainContainer">
<div id="pageContainer" >
<div id="pageContainerInner"style="background: #cdcdcd;">
</div>
</div>
<style>
BODY {
margin: 0px;
padding: 0px;
}
#pageContainer {
margin: 10px auto;
-webkit-transform-origin:50% 20%;
-webkit-transform:scale(1.37);
width: 1218px;
height: 774px;
}
#mainContainer {
width: 100%;
overflow: hidden;
}
#pageContainerInner {
position: relative;
width: 1218px;
height: 774px;
border: 1px solid #000000;
top: 0;
left: 0;
}
</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
</script>
<script type="text/javascript">
var pageWidth = 1220;
var pageHeight = 776;
var scale = 1.37;
var scaledDelta = 5; //Percentage mouse position approximation
$(document).ready(function() {
setHeight();
$(window).resize(setHeight);
});
function setHeight()
{
$('#mainContainer').css({'height': $(window).height()});
}
$('#mainContainer').mousemove(function (e) {
// Calculate the offset of scaled Div
var offsetX = $('#pageContainer').offset().left;
var offsetY = $('#pageContainer').offset().top;
// Calculate div origin with respect to screen
var originX = (-1 * offsetX) / scale;
var originY = (-1 * offsetY) / scale;
var wWdt = $(window).width();
var wHgt = $(window).height();
// Now convert screen positions to percentage
var perX = e.pageX * 100 / wWdt;
var perY = e.pageY * 100 / wHgt;
// Div content which should be visible
var pageX = perX * pageWidth / 100;
var pageY = perY * pageHeight / 100;
// Calculate scaled divs new X, Y offset
var shiftX = (originX - pageX) + (e.pageX / scale);
var shiftY = (originY - pageY) + (e.pageY / scale);
$('#pageContainerInner').css({'left': shiftX+'px', 'top': shiftY+'px'});
});
</script>
</body>
</html>
Hope this will help others.
I have posted a probable solution at http://jsfiddle.net/PYP8c/.
Below are the modified styles for your page.
BODY {
margin: 0px;
padding: 0px;
}
#mainContainer {
width: 100%;
overflow: hidden;
position: relative;
margin: 10px auto;
-webkit-transform-origin:50% 20%;
-webkit-transform:scale(1.37);
width: 1218px;
height: 774px;
border: 1px solid #000000;
}
#pageContainer {
position:absolute;
top:0px;
}
This is the javascript code for the same.
$(document).ready(function() {
//setHeight();
//$(window).resize(setHeight);
});
function setHeight()
{
$('#mainContainer').css({'height': $(window).height()});
}
$('#mainContainer').mousemove(function (e) {
var contentHeight = $("#pageContainer").height();
var minTop = 774 - contentHeight;
if(minTop>0)
minTop = 0;
var currTop = ((e.pageY-10)/774.0)*(minTop);
document.getElementById("pageContainer").style.top = currTop+'px';
});
Its just a demo on how you could get the text to move based on the mouse coordinates.
You could make a lot of changes, like adding a scrollbar that fades which gives the user a feedback about how much content is still available in both the vertical directions.
Also I have used hard coded values for height, but in your final version I would recommend you get the height of the mainContainer division dynamically.
I have a pretty huge image being displayed in a container, the image stretches with the view port as it gets resized, but as the image is so big I have added scroller buttons to the side of the page, up and down, the only problem I have now is that when I press up or down there is no limit, the user can keep going until the image is completely out of sight, how can I stop that from happening?
Here is the code I have thus far,
HTML:
<body>
<div id="wrapper">
<div class="scroll top"></div>
<div id="content">
<div id="zoom_container">
<img id="image" src="8052x2000px" />
</div>
</div>
<div class="scroll bot"></div>
</div>
</body>
CSS:
body {
width: 100%;
height: 100%;
margin: 0;
padding: 0;
}
#wrapper {
overflow: hidden;
height: 100%;
max-height: 100%;
}
#content {
min-height: 100% !important;
height: 100%;
width: 100%;
margin: 0;
padding: 0;
}
#image {
position: fixed;
top: 0;
left: 0;
width: 100%;
}
jQuery:
//side scroller bar
$('.scroll').live('click', function(){
var direction = $(this).hasClass('top');
var img_pos_top = $("#zoom_container img").position().top;
var inc = 0;
inc = $("#zoom_container img").height() / 10;
if(direction)
{
inc = $("#zoom_container img").position().top + inc;
}
else
{
inc = $("#zoom_container img").position().top - inc;
}
$("#zoom_container img").css({ position: 'relative',top: inc });
});
so as you can see I am incrementing or decrementing the top positioning of the image by 10% of it's height each click, how can I make sure the top of the image will never go further down than the top of the viewport and the bottom of the image never further up than the bottom of the viewport?
Is there a better more efficient way of achieving the same result?
Have a try this one.
<html>
<head>
<title>Canvas Sizing</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.0/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
var canvasContext;
resizeCanvas();
$(window).resize(function() { resizeCanvas() });
function resizeCanvas()
{
var w = window.innerWidth - 40;
var h = window.innerHeight - 40;
var canvasString = '<canvas id="mainCanvas" width="' + w + '" height="' + h + '">Canvas is not supported</canvas>';
$('#contentholder').empty();
$(canvasString).appendTo('#contentholder');
canvasContext = $('#mainCanvas').get(0).getContext('2d');
drawOnCanvas();
}
function drawOnCanvas()
{
var x = 15;
var y = 35;
canvasContext.font = "30pt serif";
canvasContext.fillStyle="#0f0";
canvasContext.fillText("Hello World!", x, y);
}
});
</script>
<style>
#mainCanvas
{
background-color: #000;
border: solid 3px #0F0;
}
body
{
background: #000;
}
#contentholder
{
width: 99%;
height: 99%;
margin: auto;
}
</style
</head>
<body>
<div id="contentholder"></div>
</body>