css fixed position not working in chrome - javascript

I'm doing a proof of concept site with paralax scrolling. I have 3 images on the right side of the page which link to anchors to navigate this single page site. If i put my #buttons div inside the parallax container, the buttons scroll and leave the links at the bottom of the page. If i leave them outside that div, they scroll even though ive set position to be fixed. It works perfect in FF, but not in chrome. All i need is a simple page with parallax scrolling, and three buttons on the right side of the page that persist in the same position on the screen regardless of where you have scrolled to. Why does it work in FF and not chrome? My code is below
<!DOCTYPE html>
<html>
<head>
<meta content="en-us" http-equiv="Content-Language">
<meta charset="utf-8">
<meta content="A high performance parallax scrolling example." name="description">
<meta content="Parallax Scrolling Example" name="title">
<title>Parallax Scrolling Example</title>
<style>
body {
padding: 45px;
background-color: #010001;
}
p {
font-family: Arial, Helvetica, sans-serif;
font-size: 32px;
line-height: 40px;
padding: 30px;
margin-right: 60px;
color: #FFFFFF;
}
p span {
background-color: rgba(1, 0, 1, .85);
}
a {
color: #AFDBF2;
}
h1 {
text-transform: capitalize;
font-family: "Franklin Gothic Medium", "Arial Narrow", Arial, sans-serif;
font-size: 40px;
padding: 10px;
margin: 0px;
background-color: rgba(178, 45, 0, .75);
color: #EEE;
}
#parallaxContainer {
left: 0;
position: fixed;
top: 0;
width: 100%;
z-index: -1;
}
#parallaxContainer img {
width: 100%;
height: auto;
}
#buttons {
position:fixed;
bottom:100px;
right:10px;
}
</style>
</head>
<body>
<div id="parallaxContainer">
<img src="http://4.bp.blogspot.com/_2mN0xk6r-Eo/TEh9lXrojWI/AAAAAAAAAuk/mDn5MDGetBE/s1600/0014.jpg">
</div>
<div id="buttons">
<div id="button1"><img src="images/button.png"></div>
<div id="button2"><img src="images/button.png"></div>
<div id="button3"><img src="images/button.png"></div>
</div>
<div id="content">
<h1>Some Random Star Trek Quotes</h1>
<p><span>Captain Jean-Luc Picard: Duty. A starship captain's life is filled with solemn duty. I have commanded men in battle. I have negotiated peace treaties between implacable enemies. I have represented the Federation in first contact with twenty-seven alien species. But none of this compares with my solemn duty today... as best man. Now, I know, on an occasion such as this, it is expected that I be gracious and fulsome in my praise on the wonders of this blessed union, but have the two of you considered what you were doing to me? Of course you're happy, but what about *my* needs? This is all a damned inconvenience. While you're happily settling in on the Titan, I will be training my new first officer. You all know him. He's a tyrannical martinet who will never, *ever*, allow me to go on away missions.
Data: That is the regulation, sir. Starfleet code section 12, paragraph 4...
Captain Jean-Luc Picard: Mr. Data...
Data: Sir?
Captain Jean-Luc Picard: Shut up.
Data: Yes, sir.
Captain Jean-Luc Picard: [turning to the wedding guests] 15 years I've been waiting to say that. </p></span></p>
<br>
</div>
<script src="http://www.kirupa.com/prefixfree.min.js"></script>
<script>
var requestAnimationFrame = window.requestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.msRequestAnimationFrame;
var transforms = ["transform",
"msTransform",
"webkitTransform",
"mozTransform",
"oTransform"];
var transformProperty = getSupportedPropertyName(transforms);
var imageContainer = document.querySelector("#parallaxContainer");
var scrolling = false;
var mouseWheelActive = false;
var count = 0;
var mouseDelta = 0;
//
// vendor prefix management
//
function getSupportedPropertyName(properties) {
for (var i = 0; i < properties.length; i++) {
if (typeof document.body.style[properties[i]] != "undefined") {
return properties[i];
}
}
return null;
}
function setup() {
window.addEventListener("scroll", setScrolling, false);
// deal with the mouse wheel
window.addEventListener("mousewheel", mouseScroll, false);
window.addEventListener("DOMMouseScroll", mouseScroll, false);
animationLoop();
}
setup();
function mouseScroll(e) {
mouseWheelActive = true;
// cancel the default scroll behavior
if (e.preventDefault) {
e.preventDefault();
}
// deal with different browsers calculating the delta differently
if (e.wheelDelta) {
mouseDelta = e.wheelDelta / 120;
} else if (e.detail) {
mouseDelta = -e.detail / 3;
}
}
//
// Called when a scroll is detected
//
function setScrolling() {
scrolling = true;
}
//
// Cross-browser way to get the current scroll position
//
function getScrollPosition() {
if (document.documentElement.scrollTop == 0) {
return document.body.scrollTop;
} else {
return document.documentElement.scrollTop;
}
}
//
// A performant way to shift our image up or down
//
function setTranslate3DTransform(element, yPosition) {
var value = "translate3d(0px" + ", " + yPosition + "px" + ", 0)";
element.style[transformProperty] = value;
}
function animationLoop() {
// adjust the image's position when scrolling
if (scrolling) {
setTranslate3DTransform(imageContainer,
-1 * getScrollPosition() / 2);
scrolling = false;
}
// scroll up or down by 10 pixels when the mousewheel is used
if (mouseWheelActive) {
window.scrollBy(0, -mouseDelta * 10);
count++;
// stop the scrolling after a few moments
if (count > 20) {
count = 0;
mouseWheelActive = false;
mouseDelta = 0;
}
}
requestAnimationFrame(animationLoop);
}
</script>
</body>
</html>

I think it's a problem of -webkit-transform: translate3d because it is also not working in opera and chrome and both opera and chrome use webkit transform. On the other hand it's working on IE10 and FF because they both use transform: translate3d
To make it easy you can use jquery library for your parallax effect like:
skrollr.js or stellar.js its easy and fast to create parallax.

it was a css issue. I added a z-index for the buttons, all is well. the completed code is at jsfiddle.net/ZYQBD/4 thanks to all who helped!

Related

How to write a simple marquee effect with javascript

I need everyone's help. I currently need to implement a marquee effect. The yellow box needs to be scrolled up to show the name. Every time I scroll, I have to stay in the middle of the box for 1 second before continuing to scroll. I can find such an example on the Internet. , but the logic of this program is a bit difficult for me to understand for urban beginners. I wonder if anyone would like to provide a simpler and easier-to-understand writing method if I want to achieve this marquee effect?
​​Sorry, I am a beginner in the program, the current logic More complex programs are more difficult to understand.
function slideLine(box, stf, delay, speed, h) {
var slideBox = document.getElementById(box);
var delay = delay || 1000,
speed = speed || 20,
h = h || 40;
var tid = null,
pause = false;
var s = function() {
tid = setInterval(slide, speed);
};
var slide = function() {
if (pause) return;
slideBox.scrollTop += 1;
if (slideBox.scrollTop % h == 0) {
clearInterval(tid);
slideBox.appendChild(slideBox.getElementsByTagName(stf)[0]);
slideBox.scrollTop = 0;
setTimeout(s, delay);
}
};
setTimeout(s, delay);
}
slideLine("kanban_info", "p", 1000, 25, 40);
.kanban {
position: absolute;
margin: 0 auto;
width: 278px;
height: 50px;
background-color: yellow;
left: 50%;
transform: translate(-50%);
text-align: center;
line-height: 6;
}
.kanban .kenban_wrap {
height: 38px;
transform: translateY(28px);
overflow: hidden;
}
.kanban .kenban_wrap .kanban_info {
line-height: 38px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="kanban">
<div class="kenban_wrap" id='kanban_info'>
<p class="kanban_info">Allen</p>
<p class="kanban_info">james</p>
<p class="kanban_info">jack</p>
</div>
</div>
By combining scroll-behavior with anchor tags that are programmatically clicked you can simplify it. This should be easier to understand and you can go from there, even if it might not be the best solution.
let links = document.querySelectorAll("a"); // List of links
let div = document.querySelector("div");
let index = 0;
let t = 2000; // setTimeout duration
// Change Scroll behavior to prevent the animation from the last to first list item
function scrollBeh() {
if(index == 1) {
div.style.scrollBehavior = "auto";
t = 0; // Timeout duration to 0 to prevent `1` being shown longer than other list items
} else {
div.style.scrollBehavior = "smooth";
t = 2000;
}
}
// Loop through list items
function resetInd() {
if(index < 3) {
index++;
} else {
index = 0;
}
}
function clickLinks() {
links[index].click();
resetInd();
scrollBeh();
setTimeout(clickLinks, t);
}
setTimeout(clickLinks, t);
div {
width: 200px;
height: 100px;
background-color: darkblue;
overflow: hidden;
scroll-behavior: smooth;
}
li {
height: 100px;
list-style: none;
}
a {
text-decoration: none;
color: #FFF;
font-size: 50px;
}
<div>
<ul>
<li id="one">1</li>
<li id="two">2</li>
<li id="three">3</li>
<li id="one_loop">1</li>
</ul>
</div>

Scroll to the bottom doesn't work due to font link

Can someone please explain what's going on here?
As you can see in the example, the scroll does not go all the way down to the bottom
This is of course a problem as it does not behave according to the instructions, which is:
scrollIntoView() or target.scroll (0, target.scrollHeight - target.clientHeight);
Strangely enough, it has something to do with the "font link" in "<head>", because if I use any font other than the one that has been downloaded (Poppins), it works
var html_1 = '<div class="chat_window"><div class="messages"></div></div>';
var html_2 = '<div>hello buddy</div>';
document.body.insertAdjacentHTML('beforeend', html_1);
var target = document.querySelector('.chat_window').querySelector('.messages');
for(var i = 0; i < 9; i++) {
target.insertAdjacentHTML('beforeend', html_2);
//target.scroll(0, target.scrollHeight - target.clientHeight);
target.lastElementChild.scrollIntoView();
}
body
{
font-family: Poppins; /*here, because of this the problem arise*/
}
.chat_window
{
height: 113px;
width: 339px;
border: 1px solid black;
}
.chat_window .messages
{
height: 100%;
overflow: auto;
}
<head>
<link href="http://fonts.googleapis.com/css?family=Poppins:400,300,500,600,700" rel="stylesheet">
</head>
<body></body>
The problem is the time needed to dynamically render the HTML and load the font. There are a few options, but might be seen as a little hacky.
Make sure you are using the same font somewhere else on the page. This will cause the browser to load the font (otherwise the browser may ignore the font until it is needed)
Delay the scroll a little after you render the HTML with JavaScript.
A minor change like this could work:
var html_1 = '<div class="chat_window"><div class="messages"></div></div>';
var html_2 = '<div>hello buddy</div>';
document.body.insertAdjacentHTML('beforeend', html_1);
var target = document.querySelector('.chat_window').querySelector('.messages');
for(var i = 0; i < 9; i++) {
target.insertAdjacentHTML('beforeend', html_2);
}
// A short delay, then jump to last item.
setTimeout(function(){
target.scroll(0, target.scrollHeight - target.clientHeight);
target.lastElementChild.scrollIntoView();
},500);
body{
font-family: Poppins;
}
.chat_window{
height: 113px;
width: 339px;
border: 1px solid black;
}
.chat_window .messages{
height: 100%;
overflow: auto;
}
<head>
<link href="http://fonts.googleapis.com/css?family=Poppins:400,300,500,600,700" rel="stylesheet">
</head>
<body>(forcing the font to load)</body>

Attempting to implement javascript on html page using Dreamweaver, (mouse tracker)

I have successfully yoinked the code using javascript to replace the cursor with an animated gif from this page (https://css-tricks.com/using-css-cursors/). I have successfully chucked her into Dreamweaver, I'm new to coding and I know it's way too much to start with but I want to make my website track the location of your cursor and change depending on which half of the page it's on. To be specific cursors derived from the painting: the creation of adam (the hands). Depending on which side it will switch between one of two cursors. I have found success in using a singular png as the cursor with the cursor: url() CSS method. This current method uses the CSS method of cursor: none in my style.css file.
The current javascript code is as follows
(function() {
var follower, init, mouseX, mouseY, positionElement, printout, timer;
follower = document.getElementById('follower');
printout = document.getElementById('printout');
mouseX = (event) => {
return event.clientX;
};
mouseY = (event) => {
return event.clientY;
};
positionElement = (event) => {
var mouse;
mouse = {
x: mouseX(event),
y: mouseY(event)
};
follower.style.top = mouse.y + 'px';
return follower.style.left = mouse.x + 'px';
};
timer = false;
window.onmousemove = init = (event) => {
var _event;
_event = event;
return timer = setTimeout(() => {
return positionElement(_event);
}, 1);
};
}).call(this);
and the style.css file is:
html {
cursor: url("Cursor222.png");
background: #E0CDA9;
}
#follower {
position: absolute;
top: 50%;
left: 50%;
}
#follower #circle1 {
position: absolute;
background: #0004D9;
border-radius: 50%;
height: 0em;
width: 0em;
margin-top: 0em;
margin-left: 0em;
}
#follower #circle2 {
position: absolute;
background: rgba(200,0,0,0.8);
border-radius: 50%;
height: 0em;
width: 0em;
margin-top: 0em;
margin-left: 0em;
}
I'm very new to CSS and javascript, I don't know the way to implement conditional terms like if and else, can someone chuck me some support. I get it's a big ask and I can compensate you for your time.
Here is a sample using an image:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.cursor-left {
/* cursor: url('url-to-image-1'), auto; */ // Add your cursor here
cursor: pointer;
}
.cursor-right {
/* cursor: url('url-to-image-2'), auto; */ // Add your cursor here
cursor: cell;
}
</style>
</head>
<body>
<img src="https://uploads1.wikiart.org/images/michelangelo/sistine-chapel-ceiling-creation-of-adam-1510.jpg" id="container" />
<script>
const containerElement = document.querySelector('#container');
containerElement.addEventListener('mousemove', e => {
const imageWidth = containerElement.width;
// const windowWidth = window.innerWidth; // for window
if (e.clientX <= imageWidth / 2) {
containerElement.classList.remove('cursor-right');
containerElement.classList.add('cursor-left');
} else {
containerElement.classList.remove('cursor-left');
containerElement.classList.add('cursor-right');
}
});
</script>
</body>
</html>
If you want to do it with the whole page and not a specific container, attach the event listener to the document(body might not work for you, you can see why here) and track the width with the commented code. You can add as much cursor styles as you like by altering the mouse tracking constraints.

How to stop an element to touch screen border?

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.

Unresponsive elements after button click

Background:
I started Javascript the other day and built this sketch pad:
http://frankpeelen.github.io/sketch-pad/
following alongside the instructions on:
http://www.theodinproject.com/web-development-101/javascript-and-jquery
Problem:
It's basically finished, and works fine except for when creating a new grid with the "New" button. All of a sudden the 'squares' stop responding to 'hover' events. I've searched, but have been unable to find any similar problems. Any ideas?
Code:
$(document).ready(function() {
var build = function(h, w) {
var height = h;
var width = w;
//Loop through height to create rows
for (i = 1; i <= height; i++) {
$("#sketchpadcontainer").append("<div class='row'></div>");
//Loop through width to create divs in each row
for (j = 1; j <= width; j++) {
$(".row:last-child").append("<div class='sqrcontainer'><div class='square'></div></div>");
}
}
};
//Build default 16x16 grid
build(16, 16);
$("button").click(function() {
var size = parseInt(prompt("How many squares per side would you like? Please enter a number."));
//In case the number entered > 50
if (size > 50) {
$(".row").remove();
build(50, 50);
alert("The number you entered was too large. The number 50 has been used instead.")
}
//In case a non-number is entered
else if (isNaN(size)) {
$(".row").remove();
build(16, 16);
alert("You didn't enter a number. The default of 16 has been used.")
}
//In case a number <= 50 is entered
else {
$(".row").remove();
build(size, size);
}
})
$(".square").hover(
//Mouse in
function () {
$(this).css("background-color", "blue");
},
//Mouse out
function () {} );
});
html, body, #sitecontainer {
height: 100%;
width: 100%;
margin: 0px;
}
#sketchpadcontainer {
}
button {
display: block;
margin: 0 auto;
margin-top: 2em;
margin-bottom: 1em;
}
#sketchpadcontainer {
}
.row {
text-align: center;
}
.sqrcontainer {
height: 1.5em;
width: 1.5em;
display: inline-block;
}
.square {
width: 1em;
height: 1em;
margin: .1em;
border-color: black;
border-style: solid;
border-radius: .1em;
}
<!DOCTYPE html>
<head>
<title>Sketch Pad</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type='text/javascript' src="js/javascript.js"></script>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<div id="sitecontainer">
<div id="buttoncontainer">
<button type="button">New</button>
</div>
<div id="sketchpadcontainer">
</div>
</div>
</body>
You are deleting the divs before the build method. That means the hover listeners will be deleted to. You have to add them to the .sqare elements again.
Just move
$(".square").hover(
//Mouse in
function () {
$(this).css("background-color", "blue");
},
//Mouse out
function () {} );
inside your build method
change $(".square").hover(
to $(document).on("hover" ,".square", function(){ . . . })
Ur problem in $(".square").hover( - work after $(document).ready, but after u appending new rows - document ready dont triggering, and ur elements have not events, and trigger .on work on every elems on page, even on dynamically added.

Categories