On Hover Link move Div Horizontally to current hovered Link position - javascript

I have a menu with 5 links, Each individual link has the same class and ID "navbarLink"
And I also have another div (which is a skewed shape) "#hoveredLink" that moves from 0 to the actual hovered link position (in the background) I want this shape to take the full width of the hovered link (since they're different on width since each one has more or less text). So My intention is to move this "#hoveredLink" horizontally to reach the position of the "navbarLink" actually hovered.
Haven't succeed yet!
window.onload = function() {
var bsDiv = document.getElementById("hoveredLink");
var x;
$("navbarLink").hover(function() {
x = document.getElementById("hoveredLink").left;
bsDiv.style.left = x + "px";
});
}
Can someone tell me what I'm doing wrong here?
Thanks!

It is this?
If it is not, put an example html.
var menu = document.getElementById("menu");
var up = document.getElementById("up");
menu.onmouseover = function(e){
if(e.target.nodeName != "SPAN"){ return; } // If everything is DIV, you can choose another condition to separate the children from the father.
up.style.left = e.target.offsetLeft - 10 + "px";
up.style.width = e.target.offsetWidth + 20 + "px";
};
menu.onmouseleave= function(e){ // Being the event in the parent is not lost between son and son
up.style.width = 0 + "px";
up.style.left = 0 + "px";
};
.content{
position: relative;
}
#up{
position: absolute;
top: 0px;
left: 0px;
width: 0px;
height: 3px;
background-color: red;
transition: all 0.25s;
}
#menu > span{
margin: 10px;
}
<div class="content">
<div id="up"></div>
<div id="menu">
<span>Link 1</span>
<span>Link_Link 2</span>
<span>Link3</span>
<span>Link 4...</span>
<span>L5</span>
</div>
</div>

Related

How to change the properties of a sticky up arrow button based on its position?

I have a sticky up arrow image for my webpage as follows:
HTML:
<img src = "images/sticky-btn-light.png" id = "myBtn" alt = "sticky-up-button">
And CSS:
#myBtn {
visibility: hidden;
position: fixed;
bottom: 50px;
right: 30px;
z-index: 99;
cursor: pointer;
padding: 15px;
border-radius: 10px;
width: 5%;
opacity: 0.5 ;
}
The button disappears when the user scrolls down and appears when the user scrolls up based on this JS code.
window.onscroll = function(e) {
console.log(this.oldScroll > this.scrollY);
if((this.scrollY == 0) || (this.oldScroll < this.scrollY) ){
document.getElementById('myBtn').style.visibility = 'hidden';
}
else if(this.oldScroll > this.scrollY){
document.getElementById('myBtn').style.visibility = 'visible';
}
this.oldScroll = this.scrollY;
}
Now, I want to change the color of the button based on its changing position on the screen. As I scroll the page, the sticky button will be in different sections as below.
If the sticky button is in Section A, it should be red. And if it is in Section B, it should be blue. Please note that it's the page that is moving, not the button. The button is in a fixed position.
For this, I need the id of the section in which the sticky button is overlapping at any given moment. Is there any way to get that information through JavaScript?
PS: I have adjusted the details to make things more clear. It's the page that is moving. So, if I use Element.getBoundingClientRect() for #myBtn, will I not get the same top/y values for that element wherever I scroll on the page?
You can use element.getBoundingClientRect() to get the x,y of the top left corner and the x,y of the bottom right corner of a element.
var arrow = document.getElementById('myBtn');
var arrowRect = arrow.getBoundingClientRect();
console.log(arrowRect.top, arrowRect.right, arrowRect.bottom, arrowRect.left);
var section = document.getElementById('section1');
var sectionRect = section.getBoundingClientRect();
console.log(sectionRect.top, sectionRect.right, sectionRect.bottom, sectionRect.left);
Then you can check collisions with the arrow and the section. In your case the x-axis doesn't matter:
// This checks if the arrow is touching the section
( arrowRect.bottom > sectionRect.top && arrowRect.top < sectionRect.bottom )
// This checks if the arrow isn't touching the section, then inverts it (faster)
!( arrowRect.bottom < sectionRect.top || arrowRect.top > sectionRect.bottom )
Here, I did an example for you to test and implement.
this will also help understand getBoundingClientRect even with fixed position
var arrow= document.getElementById('myBtn');
window.onscroll = function(e) {
var arrowBound = arrow.getBoundingClientRect();
var divs = document.querySelectorAll(".container > div");
divs.forEach(function(item){
var divBound = item.getBoundingClientRect();
var color= item.getAttribute("arrowColor");
if ( arrowBound.bottom > divBound.top && arrowBound.top < divBound.bottom )
{
arrow.style.borderTopColor = color
}
})
}
#myBtn {
position: fixed;
top: 10px;
left:270px;
z-index: 99;
cursor: pointer;
width: 0;
height: 0;
border-left: 20px solid transparent;
border-right: 20px solid transparent;
border-top: 20px solid #f00;
}
.container{
width:300px;
height:800px;
z-index: 81;
}
.container > div {
width:300px;
height:100px;
border:1px solid black;
}
<div class="container">
<a id = "myBtn" href = "#navbar-scroll"></a>
<div arrowColor="red"> box red </div>
<div arrowColor="blue"> box blue </div>
<div arrowColor="green"> box green </div>
</div>
You can get coords of a html element with getBoundingClientRect() method, call this function and you'll get the Y coords of element (pixels), then you can use an if conditional
function getCoords(elem) {
let box = elem.getBoundingClientRect();
let body = document.body;
let docEl = document.documentElement;
let scrollTop = window.pageYOffset || docEl.scrollTop || body.scrollTop;
let clientTop = docEl.clientTop || body.clientTop || 0;
return Math.round(box.top + scrollTop - clientTop);
}
if(getCoords(elem) > 100){
elem.className = 'your_class_name'
}
.your_class_name{
color: red;
}

Image slider - How to check if element is partially out of parent div Horizontally

I'm trying to figure out a better way to scroll the images that are farthest to the left and right into view if they are partially out of the parent div when they are clicked.
Would anyone know how I can better detect when they are partially out of view via JS?
If there a better way to go about sliding the available images into view?
Trying to get a suitable method that is not viewport width dependant to work for all the device screens.
const available_images_div = document.getElementById('available-images-div');
available_images_div.addEventListener('click', function(e) {
if (e.target.nodeName == 'IMG') {
const selected_image = e.target;
document.getElementById('active-img').src = selected_image.src;
let added_offset = selected_image.offsetLeft + selected_image.offsetWidth;
let subtracted_offset = selected_image.offsetLeft - selected_image.offsetWidth;
// Check if clicked image is partially or fully it's container's width on the right side
if (added_offset > available_images_div.clientWidth) {
// If the clicked image has an image to the right of it scroll that image into view
if (selected_image.nextElementSibling) selected_image.nextElementSibling.scrollIntoView({
behavior: "smooth"
});
// else scroll the clicked image into view
else selected_image.scrollIntoView({
behavior: "smooth"
});
}
// Check if the container was scrolled and if the clicked image is the one furthest to the left of the containers view port
if (available_images_div.scrollLeft > 0 && subtracted_offset < available_images_div.scrollLeft) {
// If the clicked image has an image to the left of it scroll that image into view
if (selected_image.previousElementSibling) selected_image.previousElementSibling.scrollIntoView({
behavior: "smooth"
});
// else scroll the clicked image into view
else selected_image.scrollIntoView({
behavior: "smooth"
});
}
}
});
#store-img-inner-div {
width: 500px;
}
#store-img-inner-div img {
width: 100%;
height: 100%;
border-radius: 5px;
border: 1px solid #ccc;
}
#available-images-div {
display: flex;
margin-top: 3rem;
overflow-x: hidden;
position: relative;
}
#available-images-div img {
width: 20%;
cursor: pointer;
}
#available-images-div img:not(:last-of-type) {
margin-right: 10px;
}
<div id="store-img-inner-div">
<div id="active-image-div">
<img id="active-img" src="https://source.unsplash.com/U2BI3GMnSSE/1600x900">
</div>
<div id="available-images-div">
<img src="https://source.unsplash.com/U2BI3GMnSSE/1600x900">
<img src="https://source.unsplash.com/wawEfYdpkag/1600x900">
<img src="https://source.unsplash.com/rRiAzFkJPMo/1600x900">
<img src="https://source.unsplash.com/rSpMla5RItA/1600x900">
<img src="https://source.unsplash.com/bIZJRVBLfOM/1600x900">
<img src="https://source.unsplash.com/jM8HUcJtXB0/1600x900">
</div>
</div>
get parent left
get parent width
get target left
get target width
const x = parent.width + parent.left - (target.width + target.left)
if(x > 0) {
console.log("passed");
} else if(x == 0) {
console.log("on line");
} else if( x < 0 ) {
console.log(" no ")
}
getting Element offset and width and height:
Element.offsetLeft || Element.getBoundingClientRect().x
sometimes one of these works if you want you can use jQuery one: ( for top and left )
if ( !elem.getClientRects().length ) {
return { top: 0, left: 0 };
}
// Get document-relative position by adding viewport scroll to viewport-relative gBCR
rect = elem.getBoundingClientRect();
win = elem.ownerDocument.defaultView;
return {
top: rect.top + win.pageYOffset,
left: rect.left + win.pageXOffset
};
for height and width you can use Element.getBoundingClientRect().width/height || Element.offsetWidth/offsetHeight
this is up to you to use offset or getBounding

how to make divs appear at the location where user clicks?

I want to have a div filled with a background color and fixed dimensions ( width and height) appear on the screen wherever I click. However, if there are 10 div's on the screen, I want to stop being able to create a div when I click on the page and have a message (alert) tell me that "I'm done".
Thank you very much.
See the example below.
var numOfDivs = 0;
document.addEventListener("click", function (e) {
if (numOfDivs < 10) {
var d = document.createElement("DIV");
d.style.top = e.clientY + "px";
d.style.left = e.clientX + "px";
document.body.appendChild(d);
numOfDivs++;
} else {
alert("Done");
}
});
div {
position: absolute;
width: 50px;
height: 50px;
background-color: red;
transform: translateX(-50%) translateY(-50%);
}
<html>
<body>
</body>
</html>

Image is not animating to the png sequence function

functionality:
When user clicks on the "Tap Here" image button, it will calls the function of "GameStart()", which will ensure that the main image "Star" moves down the page from the top of the page. The star is suppose to animate by using a png sequence logic, its proposed animated movement is to rotate between left and right giving the visual that the "Star" is climbing down a rope.
What I have done:
That is to create the function GameStart(), that calls on the method of rotation the star left to right when the user taps on the "TAP HERE" image button.
ISSUE:
The png sequence is not being called when the star moves down the page. There are 83 png files within the folder "TheStar"
What has gone wrong?? please helpI have attached the code for your reference
function GameStart() {
console.log("GameStart");
$("#Tap").click(function() {
x = document.getElementById('GameStar').offsetTop;
if (x < bottomStarLimit) {
for (var i = 0; i < 100; i++) {
if (i >= 0 && i < 10) {
$("#GameStar").attr("src", "lib/Elements/TheStar/Star_0000" + i + ".png");
x = x + step;
document.getElementById('GameStar').style.top = x + "px";
}
if (i >= 10 && i < 100) {
$("#GameStar").attr("src", "lib/Elements/TheStar/Star_000" + i + ".png");
x = x + step;
document.getElementById('GameStar').style.top = x + "px";
}
}
}
})
}
#Tap {
position: absolute;
width: 600px;
height: 650px;
margin-top: 2100px;
margin-left: 670px;
outline: 0px;
z-index: 2;
}
<div id="GamePage" style="width:100%; height:100%;z-index=1;">
<img id="GameStar" style="position: absolute; top:-6.5em; left:500px; width: auto; height: 150px, z-index:1;" type="image" src="lib/Elements/TheStar/Star_00000.png">
<input id="Tap" type="image" src="lib/Elements/Tap%20here%20button.png" onclick="GameStart()" />
</div>
There is a logic error in your code.
Inside your click function $("#Tap").click(function()
You use forloops to iterate over your code.
So every time you press the "Tap Here" image button you will iterate over ALL your image files, and you will probably only see the last image inside your folder.
Let me show how your code is now:
click
get element
check if bottom
go trough all elements
Add image to element
Increase counter
Increase distance on element.
Now what i think you are trying to do is:
Get element
When clicked
Iterate
Add image to element
Increase distance on element
Here is some code to help you along:
var player1 = $('#character'); //out player sprite
var iteratecount = 0; //needs to be outside
$('#move').click(function() { //on clicking the button
iteratecount++; //the same as iteratecount = iteratecount + 1;
player1.css('top', (iteratecount * 10) + 'px'); //times 10 because it looks better
//player1.attr("src", "lib/Elements/TheStar/Star_000" + i + ".png");
});
#character {
border-radius: 20px;
background-color: firebrick;
position: absolute;
top: 0;
width: 100px;
height: 105px;
}
.game {
position: relative;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="move">Move</button>
<div class="game">
<img id="character" href="" />
</div>

Mouse click coordinates relative to the parent div's top left corner

How to get mouse click coordinates relative to the parent div's top left corner instead of top left corner of the browser's viewport ?
Example : If you click on #mydiv in the code below, how to get the coordinates relative to #mydiv's top left corner?
mydiv.onclick = function(e) { alert(e.clientX + ' ' + e.clientY); }
#blah { position: absolute; top:50px; left:60px; width: 1000px; height: 1000px; background-color: #F0F }
#mydiv { position: absolute; top:100px; left:100px; width: 100px; height: 100px; background-color: #FF0 }
<div id="blah"><div id="mydiv">Blah</div></div>
Edited (there was a major mistake in the example).
Below is my code, sorry for using JQuery : but it gives the coordinates of parent element relative to #mydiv.
$('#mydiv').on('click', function(e) {
var offs = $('#mydiv').offset();
alert((e.clientX - offs.left) + ' ' + (e.clientY - offs.top));
});
Try it:
mydiv.onclick = function(e) {
var offsets =element_offsets(this.parentNode);
alert(e.clientX-offsets.left);
alert(e.clientY-offsets.top);
}
function element_offsets(e) {
var left = 0, top = 0;
do {
left += e.offsetLeft;
top += e.offsetTop;
} while (e = e.offsetParent);
return { left: left, top: top };
}
See the script and example from this page:
http://coursesweb.net/javascript/get-mouse-coordinates-inside-div-image_s2

Categories

Resources