Vertical positioning of divs is wrong - javascript

I am trying to make a portfolio and this is the code that is the same without the content:
$(document).ready(function() {
$('.nav-link').on('click', function() {
if ($(window).width() < 768) {
let section = $(".section#" + $(this).attr('id')).offset();
let scrollTop = $('#main-container').scrollTop() + section.top
$('#main-container').animate({
scrollTop: scrollTop
}, 500);
} else {
let section = $(".section#" + $(this).attr('id')).offset();
let scrollLeft = $('#main-container').scrollLeft() + section.left
console.log(scrollLeft);
$('#main-container').animate({
scrollLeft: scrollLeft
}, 500);
}
});
$(".container").scroll(function() {
if ($(window).width() < 768) {
let container = $(".container");
let container_height = container.height();
let pageSplit = 1 / $('.section').length
let profile_height = container_height * pageSplit;
let projects_height = container_height * pageSplit * 2;
let contact_height = container_height * pageSplit * 3;
if ($('.container').scrollTop() > contact_height + 20) {
$('.nav-link').removeClass('active');
$('.nav-link#contact').addClass('active');
} else if ($('.container').scrollTop() > profile_height && $('.container').scrollTop() < contact_height + 20) {
$('.nav-link').removeClass('active');
$('.nav-link#projects').addClass('active');
} else if ($('.container').scrollTop() < profile_height) {
$('.nav-link').removeClass('active');
$('.nav-link#profile').addClass('active');
}
} else {
let container = $(".container");
let container_width = container.width();
let pageSplit = 1 / $('.section').length
let profile_width = container_width * pageSplit;
let projects_width = container_width * pageSplit * 2;
let contact_width = container_width * pageSplit * 3;
console.log($('.container').scrollLeft());
console.log(projects_width);
if ($('.container').scrollLeft() > contact_width + 20) {
$('.nav-link').removeClass('active');
$('.nav-link#contact').addClass('active');
} else if ($('.container').scrollLeft() > profile_width && $('.container').scrollLeft() < contact_width + 20) {
$('.nav-link').removeClass('active');
$('.nav-link#projects').addClass('active');
} else if ($('.container').scrollLeft() < profile_width) {
$('.nav-link').removeClass('active');
$('.nav-link#profile').addClass('active');
}
}
});
});
function scrollHorizontally(e) {
e = window.event || e;
var delta = Math.max(-1, Math.min(1, (e.wheelDelta || -e.detail)));
document.getElementById('main-container').scrollLeft -= (delta * 55); // Multiplied by 40
e.preventDefault();
}
if (document.documentElement.clientWidth >= 768) {
if (document.getElementById('main-container').addEventListener) {
// IE9, Chrome, Safari, Opera
document.getElementById('main-container').addEventListener("mousewheel", scrollHorizontally, false);
// Firefox
document.getElementById('main-container').addEventListener("DOMMouseScroll", scrollHorizontally, false);
} else {
// IE 6/7/8
document.getElementById('main-container').attachEvent("onmousewheel", scrollHorizontally);
}
}
function scroll() {
if (document.documentElement.clientWidth >= 768) {
if (document.getElementById('main-container').addEventListener) {
// IE9, Chrome, Safari, Opera
document.getElementById('main-container').addEventListener("mousewheel", scrollHorizontally, false);
// Firefox
document.getElementById('main-container').addEventListener("DOMMouseScroll", scrollHorizontally, false);
} else {
// IE 6/7/8
document.getElementById('main-container').attachEvent("onmousewheel", scrollHorizontally);
}
} else {
if (document.getElementById('main-container').removeEventListener) {
// IE9, Chrome, Safari, Opera
document.getElementById('main-container').removeEventListener("mousewheel", scrollHorizontally, false);
// Firefox
document.getElementById('main-container').removeEventListener("DOMMouseScroll", scrollHorizontally, false);
} else {
// IE 6/7/8
document.getElementById('main-container').detachEvent("onmousewheel", scrollHorizontally);
}
}
}
/* For mobile phones: */
.container {
position: absolute;
height: 100%;
width: 100%;
background-color: #BEBAB7;
overflow: auto;
scrollbar-width: none;
white-space: normal;
}
* {
margin: 0;
}
html,
body {
background-color: #BEBAB7;
height: 100%;
font-family: sans-serif;
color: #77212E;
}
.container::-webkit-scrollbar {
display: none;
}
div.section {
display: inline-block;
height: 100%;
width: 100%;
}
.body {
margin-top: 25%;
margin-left: 25%;
width: 40%;
white-space: normal;
}
.section-pic {
width: 100px;
height: 100px;
margin-bottom: 25px;
border-radius: 100px;
border: 2px solid #77212E;
}
hr {
border-color: #77212E;
}
.github-logo {
width: 100px;
}
.nav {
position: fixed;
top: 50%;
right: 0;
transform: translateY(-50%);
z-index: 1000;
}
.nav-link {
margin: 5px;
cursor: pointer;
text-decoration: none;
position: relative;
transition: all 0.3s linear;
-webkit-transition: all 0.3s linear;
}
.nav-link::after {
content: "";
position: absolute;
width: 100%;
height: 1px;
bottom: 0;
left: 0;
background-color: #77212E;
visibility: hidden;
-webkit-transform: scaleX(0);
transform: scaleX(0);
-webkit-transition: all 0.3s ease-in-out 0s;
transition: all 0.3s ease-in-out 0s;
}
.nav-link.active::after {
visibility: visible;
-webkit-transform: scaleX(1);
transform: scaleX(1);
}
#media only screen and (min-width: 768px) {
/* For desktop: */
.container {
white-space: nowrap;
height: auto;
min-height: 100vh;
}
.body {
position: relative;
top: 50%;
margin: auto;
}
.section {
margin-top: 0;
height: 100vh;
}
.nav {
position: fixed;
top: auto;
bottom: 0;
left: 0;
right: 0;
transform: none;
}
.nav-link {
float: left;
margin: 5px;
}
}
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
<link rel="stylesheet" href="css/main.css">
<link rel="stylesheet" href="css/nav.css">
</head>
<body onresize="scroll()">
<div class="nav">
<div class="nav-link active" id="profile">
Profile
</div>
<div class="nav-link" id="projects">
Projects
</div>
<div class="nav-link" id="contact">
Contact
</div>
</div>
<div class="container" id="main-container">
<div class="section" id="profile">
<div class="body">
<h1 class="heading" id="profile-heading"><img src="img/content/profile-pic.jpg" alt="Profile Pic" class="section-pic" align="middle"> Profile</h1>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean vel euismod lorem, in condimentum leo. Nam a magna convallis, finibus odio at, tincidunt mi. Donec non erat varius, pulvinar sapien at, rhoncus lectus.
</div>
</div>
<div class="section" id="projects">
<div class="body">
<h1 class="heading" id="profile-heading"><img src="img/content/projects-pic.jpg" alt="Projects Pic" class="section-pic" align="middle"> Projects</h1>
orem ipsum dolor sit amet, consectetur adipiscing elit. Aenean vel euismod lorem, in condimentum leo. Nam a magna convallis, finibus odio at, tincidunt mi. Donec non erat varius, pulvinar sapien at, rhoncus lectus. Vivamus accumsan quam at arcu accumsan
blandit. Aliquam quis dignissim sapien, a ullamcorper risus. Phasellus accumsan neque ligula, a dapibus neque vulputate at.
</div>
</div>
<div class="section" id="contact">
<div class="body">
<h1 class="heading" id="profile-heading"><img src="img/content/contact-pic.jpg" alt="Contact Pic" class="section-pic" align="middle"> Contact</h1>
<form action="">
<input type="email">
<input type="text">
<textarea></textarea>
</form>
</div>
</div>
</div>
<script type="text/javascript" src="js/main.js" defer></script>
<script type="text/javascript" src="js/scroll.js" defer></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</body>
</html>
If you expand and shrink the result window, you can see that the page goes from a horizontal layout to a vertical layout (you have to click run when changing the layout to make the scrolling work, idk why it doesn't work in jsfiddle correctly). As you can see, if you scroll when the layout is horizontal, each 'section' of the page has a different vertical positioning. How do i make it so that the vertical positioning is at the top of the page for each section?

(Here is the fiddle of question codes: http://jsfiddle.net/6902zwjg/1/)
You assigned display: inline-block; to your sections. that cause your sections align on bottom. if you want vertical centering, you can use flex.
Example: https://codepen.io/anon/pen/zQbMzR
Float elements align on top by default.
Inline and Inline-block elements align on Bottom by default.
For vertical align, you can use flex.

While you can use Flex, you don't have to.
div.section {
display: inline-block;
height: 100%;
width: 100%;
vertical-align: top;
}

Related

Hide element if scrolled to maximum of container

I worked with this code:
$(document).ready(function() {
// Show left gradient if scrolled x value is greater than 0
$("#scroll-area").scroll(function() {
if ($("#scroll-area").scrollLeft() > 0) {
$("#left").css("display", "block");
}
// Hide left gradient if scrolled x value is 0
if ($("#scroll-area").scrollLeft() == 0) {
$("#left").css("display", "none");
}
// Calculate with of the scroll area
var fullWidth = $('#scroll-area')[0].scrollWidth;
// Doesn't work: Hide right gradient if scrolled to maximum
if ($("#scroll-area").scrollLeft() == fullWidth) {
$("#right").css("display", "none");
}
// Doesn't work: Show gradient if scrolled less than maximum
if ($("#scroll-area").scrollLeft() < fullWidth) {
$("#right").css("display", "block");
}
});
});
* {
margin: 0;
padding: 0;
font-family: sans-serif;
font-size: 20px;
}
#container {
width: 50%;
height: 120px;
background-color: grey;
position: relative;
}
#scroll-area {
white-space: nowrap;
overflow-x: auto;
height: 100%;
}
#left,
#right {
width: 50px;
height: 100%;
position: absolute;
pointer-events: none;
top: 0;
}
#left {
background: linear-gradient(90deg, orange 0%, rgba(0, 0, 0, 0) 100%);
left: 0;
display: none;
}
#right {
background: linear-gradient(-90deg, orange 0%, rgba(0, 0, 0, 0) 100%);
right: 0;
}
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<div id="container">
<div id="left"></div>
<div id="right"></div>
<div id="scroll-area">
<div id="text">Please scroll horizontally to the right side, and back again. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua.</div>
</div>
</div>
If you scroll horizontally to the end of the #text element, the gradient on the right side should be hidden. If you scroll to the left side again, the gradient should be shown again.
Has anyone an idea how to program that?
It should work as you want. Basically i calculate scrollable area in fullWidth and compare it with scrollPosition
$("#scroll-area").scroll(function() {
var fullWidth = $('#scroll-area')[0].scrollWidth - $('#scroll-area')[0].clientWidth;
var scrollPosition = $(this).scrollLeft();
if (scrollPosition > 0 && scrollPosition <= fullWidth) {
$("#left").css("display", "block");
$("#right").css("display", "block");
} else if (scrollPosition == 0) {
$("#left").css("display", "none");
$("#right").css("display", "block");
} else if (fullWidth <= scrollPosition) {
$("#left").css("display", "block");
$("#right").css("display", "none");
}
console.log('Scroll pos',scrollPosition);
console.log('Full width', fullWidth);
});
* {
margin: 0;
padding: 0;
font-family: sans-serif;
font-size: 20px;
}
#container {
width: 50%;
height: 300px;
background-color: grey;
position: relative;
}
#scroll-area {
white-space: nowrap;
overflow-x: auto;
height: 100%;
}
#left,
#right {
width: 50px;
height: 100%;
position: absolute;
pointer-events: none;
top: 0;
}
#left {
background: linear-gradient(90deg, orange 0%, rgba(0, 0, 0, 0) 100%);
left: 0;
display: none;
}
#right {
background: linear-gradient(-90deg, orange 0%, rgba(0, 0, 0, 0) 100%);
right: 0;
}
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<div id="container">
<div id="left"></div>
<div id="right"></div>
<div id="scroll-area">
<div id="text">Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua.</div>
</div>
</div>
You need to subtract the offsetWidth from the scrollWidth:
var fullWidth = $('#scroll-area')[0].scrollWidth - $('#scroll-area')[0].offsetWidth - 1 // -1 for browser compatibility
$(document).ready(function() {
// Show left gradient if scrolled x value is greater than 0
$("#scroll-area").scroll(function() {
if ($("#scroll-area").scrollLeft() > 0) {
$("#left").css("display", "block");
}
// Hide left gradient if scrolled x value is 0
if ($("#scroll-area").scrollLeft() == 0) {
$("#left").css("display", "none");
}
// Calculate with of the scroll area
var fullWidth = $('#scroll-area')[0].scrollWidth - $('#scroll-area')[0].offsetWidth - 1;
// Doesn't work: Hide right gradient if scrolled to maximum
if ($("#scroll-area").scrollLeft() >= fullWidth) {
$("#right").css("display", "none");
}
// Doesn't work: Show gradient if scrolled less than maximum
if ($("#scroll-area").scrollLeft() < fullWidth) {
$("#right").css("display", "block");
}
});
});
* {
margin: 0;
padding: 0;
font-family: sans-serif;
font-size: 20px;
}
#container {
width: 50%;
height: 120px;
background-color: grey;
position: relative;
}
#scroll-area {
white-space: nowrap;
overflow-x: auto;
height: 100%;
}
#left,
#right {
width: 50px;
height: 100%;
position: absolute;
pointer-events: none;
top: 0;
}
#left {
background: linear-gradient(90deg, orange 0%, rgba(0, 0, 0, 0) 100%);
left: 0;
display: none;
}
#right {
background: linear-gradient(-90deg, orange 0%, rgba(0, 0, 0, 0) 100%);
right: 0;
}
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<div id="container">
<div id="left"></div>
<div id="right"></div>
<div id="scroll-area">
<div id="text">Please scroll horizontally to the right side, and back again. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua.</div>
</div>
</div>

Animating content from a div that is displayed inside another div

Really new to jquery, so any help appreciated it.
Trying to solve a design challenge. I needed to display the content from a div inside another div, on hover of a third element.
Found some code that helped me put it together, but I wonder if there is a way to animate (slidedown, fadein, etc.) the content when is displayed.
Any idea how can I apply animation to the .html function when it displays the content?
var divContent = $("#explore-agility-content").html('');
$( ".industry" ).hover(
function() {
$("#explore-agility-content").html( $( this).find("#shortdesc").html() );
},
function() {
$("#explore-agility-content").html( divContent );
}
);
https://jsfiddle.net/rnwebdesigner/3wyrwd92/71/
Here are fadeIn fadeOut effects on hover and mouseout
check this fiddle
https://jsfiddle.net/parthjasani/3wyrwd92/72/
var divContent = $("#explore-agility-content").html('');
$(".industry").hover(
function () {
$("#explore-agility-content").html($(this).find("#shortdesc").html());
$("#explore-agility-content .wb").hide().fadeIn()
},
function () {
$("#explore-agility-content .wb").fadeOut(function () {
$("#explore-agility-content").html(divContent);
})
}
);
You can add and remove css classes which can contain several properties to be transitioned on mouse enter and leave..
See snippet below (solution 1)
$('.image').mouseenter(function(){
$(".text").addClass("animate")
});
$('.image').mouseleave(function(){
$(".text").removeClass("animate")
});
.image {
width: 50px;
height: 50px;
display: block;
background-color: red;
}
.text {
background-color: white;
padding:40px;
transition:all 0.5s;
}
.left {
display:block;
height:400px;
width: 400px;
background: url('http://i.stack.imgur.com/jGlzr.png') no-repeat 0 0 scroll;
background-color:#0C0C0C;
background-size: 100% 100%;
}
.animate{
opacity:1 !important;
padding-top:50px;
}
.noanimate{
opacity:0;
padding-top:-50px
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="image"></div>
<div class="left">
<div class="text noanimate">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed tincidunt consequat tristique. Curabitur vestibulum semper nulla id ornare.
</div>
</div>
Solution 2 - using hover function instead of mounseenter and leave
$('.image').hover(function(){
$(".text").toggleClass("animate")
});
.image {
width: 50px;
height: 50px;
display: block;
background-color: red;
}
.text {
background-color: white;
padding:40px;
transition:all 0.5s;
}
.left {
display:block;
height:400px;
width: 400px;
background: url('http://i.stack.imgur.com/jGlzr.png') no-repeat 0 0 scroll;
background-color:#0C0C0C;
background-size: 100% 100%;
}
.animate{
opacity:1 !important;
padding-top:50px;
}
.noanimate{
opacity:0;
padding-top:-50px
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="image"></div>
<div class="left">
<div class="text noanimate">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed tincidunt consequat tristique. Curabitur vestibulum semper nulla id ornare.
</div>
</div>

Display a Modal on button click using Jquery

I want to display my Modal on button click. Below is my code.
<input type="button" id="button1" value="Button" onclick="myFunction()"/>
<div id="openModal" class="modalDialog">
<div>
X
<h2>
Modal Box</h2>
<p>
Hello world</p>
</div>
</div>
This is my unfinished script.
<script type="text/javascript">
$(document).ready(function () {
});
</script>
show openModal div on button1 click.
$('#button1').on('click', function() {
$('#openModal').show();
});
No need of onclick="myFunction()" on button
Let's try...
Simple popup model created by using jquery, HTML, and CSS.
$(function() {
// Open Popup
$('[popup-open]').on('click', function() {
var popup_name = $(this).attr('popup-open');
$('[popup-name="' + popup_name + '"]').fadeIn(300);
});
// Close Popup
$('[popup-close]').on('click', function() {
var popup_name = $(this).attr('popup-close');
$('[popup-name="' + popup_name + '"]').fadeOut(300);
});
// Close Popup When Click Outside
$('.popup').on('click', function() {
var popup_name = $(this).find('[popup-close]').attr('popup-close');
$('[popup-name="' + popup_name + '"]').fadeOut(300);
}).children().click(function() {
return false;
});
});
body {
font-family:Arial, Helvetica, sans-serif;
}
p {
font-size: 16px;
line-height: 26px;
letter-spacing: 0.5px;
color: #484848;
}
/* Popup Open button */
.open-button{
color:#FFF;
background:#0066CC;
padding:10px;
text-decoration:none;
border:1px solid #0157ad;
border-radius:3px;
}
.open-button:hover{
background:#01478e;
}
.popup {
position:fixed;
top:0px;
left:0px;
background:rgba(0,0,0,0.75);
width:100%;
height:100%;
display:none;
}
/* Popup inner div */
.popup-content {
width: 500px;
margin: 0 auto;
box-sizing: border-box;
padding: 40px;
margin-top: 20px;
box-shadow: 0px 2px 6px rgba(0,0,0,1);
border-radius: 3px;
background: #fff;
position: relative;
}
/* Popup close button */
.close-button {
width: 25px;
height: 25px;
position: absolute;
top: -10px;
right: -10px;
border-radius: 20px;
background: rgba(0,0,0,0.8);
font-size: 20px;
text-align: center;
color: #fff;
text-decoration:none;
}
.close-button:hover {
background: rgba(0,0,0,1);
}
#media screen and (max-width: 720px) {
.popup-content {
width:90%;
}
}
<!DOCTYPE html>
<html>
<head>
<title> Popup </title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
</head>
<body>
<a class="open-button" popup-open="popup-1" href="javascript:void(0)"> Popup
Preview</a>
<div class="popup" popup-name="popup-1">
<div class="popup-content">
<h2>Model </h2>
<p>Model content will be here. Lorem ipsum dolor sit amet,
consectetur adipiscing elit. Aliquam consequat diam ut tortor
dignissim, vel accumsan libero venenatis. Nunc pretium volutpat
convallis. Integer at metus eget neque hendrerit vestibulum.
Aenean vel mattis purus. Fusce condimentum auctor tellus eget
ullamcorper. Vestibulum sagittis pharetra tellus mollis vestibulum.
Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
<a class="close-button" popup-close="popup-1" href="javascript:void(0)">x</a>
</div>
</div>
</body>
</html>
Change show() to modal.show();
$('#button1').on('click', function() {
$('#openModal').modal('show');
});
You probably have to set visibility:hidden; to the div, and set it to visible onclick

Preventing content visibility underneath a transparent fixed navigation bar

I have a semi-transparent navigation bar that has a fixed position at the top of the window, and content underneath it.
I'd like to make it so that the #content isn't ever visible underneath the navigation bar. Setting the top margin of the content to the same height as the navigation bar works, when the user is at the top of the page. However when the user scrolls down, the content becomes visible underneath the navigation bar.
Basically I'm trying to push/clip the top of the content div, so none of its content is ever visible underneath the navigation bar.
The navigation bar's transparency is particularly important, so simply having an opaque gray background won't work for what I need.
Any suggestions for accomplishing what I'm trying to do?
Code:
http://jsfiddle.net/NAMka/
HTML:
<nav id="top">
<div style="margin: 12px;">foo</div>
</nav>
<div id="content"></div>
CSS:
#top {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 60px;
color: white;
background: rgba(0, 0, 0, 0.7);
}
#content {
margin-top: 60px;
}
JS:
// This is a little cleaner than just manually repeating the p tags.
for (var i = 0; i <= 20; i++) {
$('#content').append('<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut iaculis dolor in sem tempus rutrum. Nullam mattis sodales mi, eu bibendum ante porta quis. Phasellus dui sem, imperdiet at massa in, imperdiet vestibulum leo.</p>');
}
Some mock-ups of what I'm trying to do
This is what the fiddle will look like if you scroll down a little bit. Notice how the content is visible underneath the navigation bar.
Ideally, I'd like the content to be clipped, so it isn't visible underneath the navigation bar.
Update:
Although not ideal, I figured out a somewhat hackish way to achieve what I want involving some JS and the overflow:hidden CSS setting. It seems to work well enough for my purposes.
http://jsfiddle.net/NAMka/4/
HTML:
<nav id="top">
<div style="margin: 12px;">foo</div>
</nav>
<div id="container">
<div id="veil">
<div id="content"></div>
</div>
</div>
CSS:
#top {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 60px;
color: white;
background: rgba(0, 0, 0, 0.7);
}
#container {
background: yellow;
margin-top: 60px;
z-index: -1;
position: relative;
}
#veil {
background: red;
position: absolute;
width: 100%;
left: 0px;
bottom: 0px;
overflow: hidden;
}
#content {
background: blue;
position: absolute;
left: 0px;
bottom: 0px;
}
JS:
for (var i = 0; i <= 6; i++) {
$('#content').append('<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut iaculis dolor in sem tempus rutrum. Nullam mattis sodales mi, eu bibendum ante porta quis. Phasellus dui sem, imperdiet at massa in, imperdiet vestibulum leo.</p>');
}
var height = $('#content').height();
$('#container').height(height);
$('#veil').height(height);
$(window).scroll(function() {
$('#veil').height($('#content').height() - $(window).scrollTop() );
});
You can add a white div that sits beneath the navbar but above the content.
http://jsfiddle.net/naLz7/
HTML
<nav id="top">
<div style="margin: 12px;">foo</div>
</nav>
<div id="bottom"></div>
<div id="content"></div>
CSS
#top {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 60px;
color: white;
background: rgba(0, 0, 0, 0.7);
z-index: 1;
}
#bottom {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 60px;
background: #fff;
z-index: 0;
}
#content {
margin-top: 60px;
}

Chrome gives wrong element width

I'm making a tooltip class in Mootools that depends on getting the width of the tooltip element to centre it over the target.
It works nicely in all browsers except Chrome, which comes up with two wildly different numbers for the element width on each reload of the page. When I set a width of 100 and height 20 in the CSS, the Chrome web dev inspector shows the dimensions correctly. But when I refresh the page Chrome logs out a mad figure like 1904, and my element is positioned far away to the side.
I've tried using these different ways of getting the width, either hiding the tooltip with display:none or z-index:
getDimensions()
getSize()
getStyle('width')
element.offsetWidth
all with similar results. Can any kind person suggest a workaround, or tell me why Chrome is behaving in this way?
Thanks!
Fred
Here's my JS:
Tooltip = new Class({
Implements: Events,
Implements: Options,
options: {
target: '', // Single element or array of elements
tip: '' // Element to show
},
initialize: function(options) {
this.setOptions(options);
this.setValues();
this.attachEvents();
},
setValues: function() {
this.target = this.options.target;
this.tip = this.options.tip;
this.tip.setStyle('z-index', -1); // Hide tip element
if (this.target == null || this.tip == null) return; // We don't have required elements, so return
this.showing = false;
this.tipMousedOver = false;
this.tipDimensions = this.tip.getSize(); // Getting width
console.log(this.tip);
console.log(this.tipDimensions.x);
console.log(this.tip.offsetWidth);
this.tipFx = new Fx.Morph(this.tip, {
duration: 350,
transition: Fx.Transitions.Sine.easeIn,
link: 'cancel',
onComplete: function() {
if (this.showing) this.showing = false;
else this.showing = true;
}.bind(this)
});
},
attachEvents: function() {
this.tip.addEvent('mouseenter', function(e) {
this.tipMousedOver = true;
document.removeEvents('click');
}.bind(this));
this.tip.addEvent('mouseleave', function(e) {
document.addEvent('click', this.bodyClick.bind(this));
}.bind(this));
if (typeOf(this.target) == 'element') {
this.target.addEvent('click', this.toggleTip.bind(this));
} else {
this.target.each(function(item, index){
item.addEvent('click', this.toggleTip.bind(this));
}.bind(this));
}
},
toggleTip: function(e) {
e.stopPropagation();
if (!this.showing) {
// HIdden, so show
var posn = e.target.getPosition();
var vPosn = posn.y;
var hPosn = posn.x;
var targetWidth = e.target.getSize().x;
this.tip.setStyle('z-index', 1);
this.tip.setStyle('top', vPosn - (this.tipDimensions.y + 10));
this.tip.setStyle('left', (hPosn + targetWidth /2) - (this.tipDimensions.x / 2)); // Positions middle of tip over middle of target
console.log('targetWidth: ' + targetWidth + ' tipDimensions.x: ' + this.tipDimensions.x);
this.tipFx.start({'opacity': [0, 1]});
document.addEvent('click', this.bodyClick.bind(this));
} else {
// Visible, so hide
if (!this.tipMousedOver) {
this.tipFx.start({'opacity': 0});
this.tip.setStyle('z-index', 1);
document.removeEvent('click', this.bodyClick);
}
}
},
bodyClick: function(e) {
this.tipFx.start({'opacity': 0});
this.tip.setStyle('z-index', 1);
document.removeEvents('click', this.bodyClick);
}
});
window.addEvent('domready', function(){
new Tooltip({
target: $('comments-list').getElements('.shareLink'),
tip: $('shareTip')
});
});
HTML:
<!DOCTYPE html>
<html>
<head>
<script src="js/mootools-core-1.3.2-full-compat.js"></script>
<script src="js/mootools-more-1.3.2.1.js"></script>
<script src="comments_new_click.js"></script>
<link href="comments_new.css" type="text/css" rel="stylesheet">
</head>
<body>
<ul id="comments-list">
<!-- START COMMENT ITEM -->
<li id="CommentKey-f8b1-45f2-b4f6-68ba740ca9c3" class="commentItem">
<div class="commentTop clrd">
<span class="badges">
<img style="width: 32px; height: 32px;" src="" alt="" title="">
<img style="width: 32px; height: 32px;" src="" alt="" title="">
</span>
<a class="avatar" href="javascript:;" title="">
<img src="" alt="Photo of editor1">
</a>
<a class="username" href="javascript:;" title="">And Finally</a>
</div>
<div class="commentBody clrd">
<div class="commentOver">
<div class="submDateAndTime">26 April 2011</div>
</div>
<div class="commentSide">
<div class="likeDislike">
<a class="pluck-like alreadyvoted" href="javascript:;" title="">Like</a>
<span class="pluck-score">00000</span>
<a class="pluck-dislike" href="javascript:;" title="">Dislike</a>
</div>
</div>
<div class="commentText">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur a sapien vitae enim sagittis sodales at sit amet leo. Aenean cursus euismod blandit. Suspendisse potenti. Pellentesque vestibulum nisi id dui aliquet consequat. Nulla egestas tortor vel metus dapibus luctus. Nullam rhoncus ullamcorper lorem, non vehicula nulla euismod viverra. Morbi tempus dui ut ipsum interdum ut dapibus est venenatis.
</div>
</div>
<div class="commentBottom clrd">
<div class="getReplies">
See Replies
<span>2</span>
</div>
<!-- To delete -->
<div style="display:block;clear:both;float:none;height:0"></div>
</div>
<!-- REPLIES -->
<div id="nestedcommentslist-CommentKey:f8b1-45f2-b4f6-68ba740ca9c3" class="repliesWrapper"></div>
<!-- END REPLIES -->
</li>
<!-- END COMMENT ITEM -->
<!-- START COMMENT ITEM -->
<li id="CommentKey-f8b1-45f2-b4f6-68ba740ca9c3" class="commentItem">
<div class="commentTop clrd">
<span class="badges">
<img style="width: 32px; height: 32px;" src="http://z.x.co.uk/ver1.0/Content/images/store/5/6/3262-4af5-8654-ef59a25b24e1.Full.png" alt="" title="">
<img style="width: 32px; height: 32px;" src="http://z.x.co.uk/ver1.0/Content/images/store/5/6/3262-4af5-8654-ef59a25b24e1.Full.png" alt="" title="">
</span>
<a class="avatar" href="javascript:;" title="">
<img src="http://z.x.co.uk/ver1.0/Content/images/store/13/3/f175-45b8-931b-28619aadfd2a.Small.png" alt="Photo of editor1">
</a>
<a class="username" href="javascript:;" title="">And Finally</a>
</div>
<div class="commentBody clrd">
<div class="commentOver">
<div class="submDateAndTime">26 April 2011</div>
</div>
<div class="commentText">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur a sapien vitae enim sagittis sodales at sit amet leo. Aenean cursus euismod blandit. Suspendisse potenti. Pellentesque vestibulum nisi id dui aliquet consequat.
</div>
</div>
<div class="commentBottom clrd">
<div class="getReplies">
See Replies
<span>2</span>
</div>
<div class="share">
Report abuse
Share
</div>
<!-- To delete -->
<div style="display:block;clear:both;float:none;height:0"></div>
</div>
<!-- REPLIES -->
<div id="nestedcommentslist-CommentKey:f8b1-45f2-b4f6-68ba740ca9c3" class="repliesWrapper"></div>
<!-- END REPLIES -->
</li>
<!-- END COMMENT ITEM -->
</ul>
<div id="shareTip" class="popup">Share and things</div>
</body>
</html>
CSS:
body {
font-family: Arial,Helvetica,sans-serif;
font-size: 62.5%;
}
#comments-list {
width: 480px;
margin: 20px auto;
border: 1px solid #ccc;
list-style-type: none;
padding: 0;
}
.commentItem {
margin-left: 0;
padding-left: 0;
font-size: 13px;
}
.avatar {
margin-right: 5px;
}
.avatar img {
width: 45px;
height: 45px;
}
.commentTop {
position: relative;
padding: 5px;
min-height: 48px;
background: #e8e8eb;
}
.username {
position: absolute;
top: 5px;
height: 1em;
font-size: 14px;
text-decoration: none;
}
.badges {
float: right;
}
.badges img {
margin-left: 2px;
}
.commentBody {
padding: 5px;
background: #f3f2f2;
}
.commentText {
margin-right: 75px;
line-height: 16px;
}
.commentOver {
clear: both;
float: none;
height: 14px;
padding: 0 3px 10px 0;
}
.submDateAndTime {
float: left;
color: #777;
font-size: 11px;
}
.getReplies {
float: left;
padding: 0;
}
.getReplies a {
background-color: #ED9430; /* Put elsewhere */
background-image: url("http://z.x.co.uk/images/comments-wide.png");
background-position: -508px -245px;
background-repeat: no-repeat;
display: block;
float: left;
height: 20px;
text-indent: -9999px;
width: 60px;
}
.getReplies span {
background-image: url("http://z.x.co.uk/images/comments-wide.png");
background-position: -569px -245px;
background-repeat: no-repeat;
display: block;
float: left;
font-size: 14px;
font-weight: bold;
height: 21px;
padding-left: 2px;
text-align: center;
width: 41px;
line-height: 19px;
}
.commentBottom {
padding: 5px;
background: #f3f2f2;
}
.share {
float: right;
}
.popup {
position: absolute;
border: 1px solid #ccc;
padding: 10px;
background: #fff;
z-index: 1;
}
.hidden {
display: none;
}
#shareTip {
width: 100px;
height: 20px;
overflow: hidden;
}
=======================================
LATER
For anyone else coming across a similar problem, I found it went away when I measured the tip element right before showing it, instead of when the object's initialised. So I changed my reveal method to:
toggleTip: function(e) {
e.stopPropagation();
if (!this.showing) {
// HIdden, so show
var posn = e.target.getPosition();
var targetPosnY = posn.y;
var targetPosnX = posn.x;
var targetWidth = e.target.getSize().x;
var targetHeight = e.target.getSize().y;
var tipSize = this.tip.getSize();
var tipPosnY = targetPosnY - (tipSize.y + 10);
var tipPosnX = targetPosnX - (targetWidth / 2);
this.tip.setStyle('z-index', 1);
this.tip.setPosition({x: tipPosnX, y: tipPosnY});
this.tipFx.start({'opacity': 1});
document.addEvent('click', this.bodyClick.bind(this));
} else {
// Visible, so hide
if (!this.tipMousedOver) {
this.tipFx.start({'opacity': 0});
this.tip.setStyle('z-index', 1);
document.removeEvent('click', this.bodyClick);
}
}
},
I also found that setPosition() is a more reliable way of positioning the element than setStyle().
If you target the recent browsers only you can use window.getComputedStyle that returns all the css properties and values as they are painted on the screen.
Or just make a workaround for chrome using it.

Categories