Show hover card left right based on element left right? - javascript

My HTML has a div and when I hover the div a card will be displayed on the right side. When the div is in left side then this still show right side. When I reduce the browser width then this card partially show the detail.
How to automatically position using jquery.
var thisEl = $(this);
var offsets = thisEl.offset();
var thisElTopOffset = offsets.top;
var thisElLeftOffset = offsets.left;
This will show as i mentioned in the image. But i try to position the div to left when the elements are in right.
Code: I tried so far
allHoverCardTriggers.on({
click: function(event) {
event.preventDefault();
var thisEl = $(this);
cardTimer = setTimeout(function(){
var docWidth = $(document).width();
var rightSide = false;
//return user id
var userLink = thisEl.attr('href');
if($('.ViewProfilePage').length && $('img.lia-user-avatar-profile',thisEl).length){
var userLink = document.location.href;
} else if(thisEl.attr('href')=='#'){
return false;
}
var thisLen = (userLink).split('/');
thisUserID = (thisLen)[thisLen.length-1];
var thisCard = $('.profileCard[data-user='+thisUserID+']',cardWrapper);
var offsets = thisEl.offset();
var thisElTopOffset = offsets.top;
var thisElLeftOffset = offsets.left;
if(thisCard.length && $('.profileCard[data-user='+thisUserID+'] .preloader',cardWrapper).length<1)
{
$('.profileCard',cardWrapper).hide();
rightSide?thisCard.addClass('rightArrow'):thisCard.removeClass('rightArrow');
thisCard.delay(500).css({'top':thisElTopOffset,'left':thisElLeftOffset}).stop().show();
}
else
{
var ajaxReturn = '';
thisCard.remove();
//profile card wrapper markup
var rightArrowClass = rightSide?'rightArrow':'';
var profileCardHtml = '<div class="profileCard '+rightArrowClass+'" style="display:block;top:'+thisElTopOffset+'px;left:'+thisElLeftOffset+'px;" data-user="'+thisUserID+'"><div class="inner"><img src="/html/assets/feedback_loading_trans.gif" class="preloader" style="margin:80px auto;display:block;" /></div></div>';
$.when(
//get the background
$.ajax({
type: 'GET',
url: userApiUrl+thisUserID,
dataType: 'html',
success: function(data) {
$('.profileCard',cardWrapper).hide();
ajaxReturn = data;
}
})
)
.done(function(){
cardWrapper.append(profileCardHtml);
$('.profileCard[data-user='+thisUserID+']',cardWrapper).eq(0).empty().html(ajaxReturn);
if($('.profileCard[data-user='+thisUserID+'] .preloader',cardWrapper).length){
$('.profileCard[data-user='+thisUserID+'] .preloader',cardWrapper).parents('div.profileCard').remove();
}
})
.fail(function(){
// Hide if failed request
$('.profileCard',cardWrapper).hide();
});
}
}
},400);
},
mouseleave: function() {
clearTimeout(cardTimer);
if($('.profileCard[data-user='+thisUserID+']',cardWrapper).length){
$('.profileCard[data-user='+thisUserID+']',cardWrapper).delay(500).fadeOut('fast');
}
}
});
}

Here is a jQuery solution. Prior to displaying the popup, the script checks if the offset position of the trigger div plus the popup width falls beyond the screen width and adjusts the popup position accordingly.
hover = function(e) {
//var position = e.position();
var popup = $('.popup');
popup.attr('style', '');
if (e.offsetLeft + popup.outerWidth() > $( window ).width()) {
// adjust for screen width
popup.css({
right: $( window ).width() - e.offsetLeft - e.offsetWidth + 'px',
top: e.offsetTop - popup.outerHeight()
});
}
else {
// position normally
popup.css({
left: e.offsetLeft,
top: e.offsetTop - popup.outerHeight()
});
}
popup.show();
}
hide = function() {
$('.popup').hide();
}
.left-hover {
position:absolute;
left:20px;
top:80px;
border:1px solid black;
}
.right-hover {
position:absolute;
right:20px;
top:80px;
border:1px solid black;
}
.popup {
position:absolute;
display:none;
border:1px solid red;
width:100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="left-hover" onmouseover="hover(this)" onmouseout="hide()">Hover me</div>
<div class="right-hover" onmouseover="hover(this)" onmouseout="hide()">Hover me</div>
<div class="popup">My popup</div>

Related

Find position of multiple draggable elements

How would i be able to find the top, left, bottom and right position of multiple moveable elements on a page? I tried jQuery .position() for it, however the function gives me the position of only the most recent moveable element created (div). Here's the code -
Finding Position -
$(document).on('click', function(e) {
var createdWindow = $(nWindow).position();
var createdWindow_right = $(nWindow).position().left + $(nWindow).width();
var createdWindow_bottom = $(nWindow).position().top + $(nWindow).height();
console.log("Top position: " + createdWindow.top + ", Left position: " + createdWindow.left + ", right position: " + createdWindow_right + ", bottom position: " + createdWindow_bottom);
// returns an object with x/y coordinates of the top-left corner of the element
});
Div Creation -
function windowProperties(containment,x,y,width,height){ //New Window Style and jQuery Functions
$(containment).append('<div id="window'+divCount+'"><p id="para'+divCount+'">Drop Here</p></div>');
nWindow = document.getElementById('window'+divCount);
paragraph = document.getElementById('para'+divCount);
paragraph.style.color = "black";
paragraph.style.fontSize = "20px";
paragraph.style.fontWeight = "bold";
paragraph.style.padding = "10px";
paragraph.style.textAlign = "center";
nWindow.style.width = width+"px"; //680
nWindow.style.position = "absolute";
nWindow.style.height = height+"px"; //294.75
nWindow.style.opacity = "0.5";
nWindow.style.background = "white";
nWindow.style.zIndex = "200";
nWindow.style.top = x+"px";
nWindow.style.left = y+"px";
};
Use draggable event property of an element and send event on drag events.
For Example:-
<div draggable = true ondragstart="abc(event)>
//some HTML CODE
</div>
<script>
function abc(event)
{
console.log(event) // here in this event you get all the data of draggable elements
}
</script>
Consider the following example.
$(function() {
$.fn.getPosition = function() {
var results = $(this).position();
results.right = results.left + $(this).width();
results.bottom = results.top + $(this).height();
return results;
}
$(".drag").draggable({
containment: "parent",
stop: function(e, ui) {
console.log($(this).attr("id"), $(this).getPosition());
}
});
});
.cnt {
width: 340px;
height: 340px;
border: 1px solid black;
}
.drag {
width: 20px;
height: 20px;
background: #ccc;
}
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<div class="cnt">
<div class="drag" id="box-1"></div>
<div class="drag" id="box-2"></div>
</div>
This creates a function that can get you the full position. You can then use that in stop callback for a Drag action.

Fade in on Scroll Plain JavaScript No JQuery

I'm trying to implement a text fade in on scroll similar to this https://codepen.io/hollart13/post/fade-in-on-scroll.
$(function(){ // $(document).ready shorthand
$('.monster').fadeIn('slow');
});
$(document).ready(function() {
/* Every time the window is scrolled ... */
$(window).scroll( function(){
/* Check the location of each desired element */
$('.hideme').each( function(i){
var bottom_of_object = $(this).position().top + $(this).outerHeight();
var bottom_of_window = $(window).scrollTop() + $(window).height();
/* If the object is completely visible in the window, fade it it */
if( bottom_of_window > bottom_of_object ){
$(this).animate({'opacity':'1'},1500);
}
});
});
});
However, I do not want to use JQuery. I want to accomplish this using plain JavaScript. Unfortunately, most of the examples online are JQuery based and there's very little with plain JavaScript.
This is what I've attempted so far to "translate" this JQuery into plain JS. It's not working. Could anyone point at where I went wrong?
window.onscroll = function() {myFunction()};
function myFunction() {
var elements = document.getElementsByClassName("target");
for(var i = 0; i < elements.length; i++){
var bottomOfObject = elements[i].getBoundingClientRect().top +
window.outerHeight;
var scrollTop = (window.pageYOffset !== undefined) ? window.pageYOffset :
(document.documentElement || document.body.parentNode ||
document.body).scrollTop;
var bottomOfWindow = scrollTop + window.innerHeight;
if(bottomOfWindow > bottomOfObject){
$(this).animate({'opacity': '1'}, 1500);
}
}
console.log(bottomOfObject);
}
Thanks in advance!
Try this simple vanilla JavaScript solution
var header = document.querySelector("#header");
window.onscroll = function() {
if (document.body.scrollTop > 50) {
header.className = "active";
} else {
header.className = "";
}
};
#header {
background-color: black;
transition: all 1s;
position: fixed;
height: 40px;
opacity: 0;
right: 0;
left: 0;
top: 0;
}
#header.active {
opacity: 1;
}
#wrapper {
height: 150vh;
}
<html>
<body>
<div id="header"></div>
<div id="wrapper"></div>
</body>
</html>
Essentially there is an element positioned on the top of the screen which is invisible at first (with opacity 0) and using javascript I add an class to it that makes it visible (opacity 1) what makes it slowly visible instead of instantly is the transition: all 1s;
Here's my version with dynamic opacity based on scroll position, I hope it helps
Window Vanilla Scroll
function scrollHandler( event ) {
var margin = 100;
var currentTop = document.body.scrollTop;
var header = document.querySelector(".header");
var headerHeight = header.getBoundingClientRect().height;
var pct = (currentTop - margin) / ( margin + headerHeight );
header.style.opacity = pct;
if( pct > 1) return false;
}
function addListeners() {
window.addEventListener('scroll' , scrollHandler );
document.getElementById("click" , function() {
window.scrollTop = 0;
});
}
addListeners();

Horizontal scroll only if necessary

I'm having a horizontal scrolling page where arrows are indicated to scroll. I'm using the following code which works fine.
HTML:
<div id="container">
<div id="parent">
<div class="contentBlock">1</div>
<div class="contentBlock">2</div>
<div class="contentBlock">3</div>
<div class="contentBlock">4</div>
<div class="contentBlock">5</div>
</div>
<span id="panLeft" class="panner" data-scroll-modifier='-1'>Left</span>
<span id="panRight" class="panner" data-scroll-modifier='1'>Right</span>
CSS:
#container{
width:600px;
overflow-x:hidden;
}
#parent {
width:6000px;
}
.contentBlock {
font-size:10em;
text-align:center;
line-height:400px;
height:400px;
width:500px;
margin:10px;
border:1px solid black;
float:left;
}
.panner {
border:1px solid black;
display:block;
position:fixed;
width:50px;
height:50px;
top:45%;
}
.active {
color:red;
}
#panLeft {
left:0px;
}
#panRight {
right:0px;
}
Javascript:
(function () {
var scrollHandle = 0,
scrollStep = 5,
parent = $("#container");
//Start the scrolling process
$(".panner").on("mouseenter", function () {
var data = $(this).data('scrollModifier'),
direction = parseInt(data, 10);
$(this).addClass('active');
startScrolling(direction, scrollStep);
});
//Kill the scrolling
$(".panner").on("mouseleave", function () {
stopScrolling();
$(this).removeClass('active');
});
//Actual handling of the scrolling
function startScrolling(modifier, step) {
if (scrollHandle === 0) {
scrollHandle = setInterval(function () {
var newOffset = parent.scrollLeft() + (scrollStep * modifier);
parent.scrollLeft(newOffset);
}, 10);
}
}
function stopScrolling() {
clearInterval(scrollHandle);
scrollHandle = 0;
}
}());
You can also view the code in a WordPress-Installation right here: http://ustria-steila.ch/test
The arrows and the scroll works really well - but I have different sites with different amounts of text and images. So some pages need a horizontal scroll and some not. How can I add some kind of if-condition to display the arrows only if there is a horizontal overflow?
Your JavaScript code should go like this:
(function () {
var scrollHandle = 0,
scrollStep = 5,
parent = $("#container");
if(checkOverflow()){
$(".panner").show();
}
else
$(".panner").hide();
//Start the scrolling process
$(".panner").on("mouseenter", function () {
var data = $(this).data('scrollModifier'),
direction = parseInt(data, 10);
$(this).addClass('active');
startScrolling(direction, scrollStep);
});
//Kill the scrolling
$(".panner").on("mouseleave", function () {
stopScrolling();
$(this).removeClass('active');
});
//Actual handling of the scrolling
function startScrolling(modifier, step) {
if (scrollHandle === 0) {
scrollHandle = setInterval(function () {
var newOffset = parent.scrollLeft() + (scrollStep * modifier);
parent.scrollLeft(newOffset);
}, 10);
}
}
function stopScrolling() {
clearInterval(scrollHandle);
scrollHandle = 0;
}
function checkOverflow()
{
var el=document.getElementById('container');
var curOverflow = el.style.overflowX;
if ( !curOverflow || curOverflow === "visible" )
el.style.overflowX = "hidden";
var isOverflowing = el.clientWidth < el.scrollWidth;
el.style.overflowX = curOverflow;
return isOverflowing;
}
}());

Adding Height to another Div

I'm adding 50px on every click on my div header, and i want to make my div main has the same height of header when header is bigger than it.
I don't know why its not working.
I have this script
$(function () {
var alturaHeader = $('header').height();
var alturaMain = $('.main').height();
$('button').click(function(){
$('header').height(function(index, height){
return (height + 50);
});
console.log(alturaHeader);
if (alturaMain < alturaHeader) {
alert("test");
$('.main').css({'min-height': alturaHeader });
}
});
});
any suggestions ?
JS Fiddle: http://jsfiddle.net/JWf7u/
Thanks.
There is you fiddle code You should update the height of div everytime it changes.
var alturaHeader = $('header').height();
var alturaMain = $('.main').height();
$('button').click(function(){
$('header').height(function(index, height){
return (height + 50);
});
alturaHeader = $('header').height()
if (alturaMain < alturaHeader) {
$('.main').css({'min-height': alturaHeader });
}
});
why dont u use the css property height:100% for main (child) div..
check the below
$(function () {
var alturaHeader = $('.header').height();
var alturaMain = $('.main').height();
$('button').click(function(){
$('.header').height(function(index, height){
return (height + 50);
});
// below is not required we are using css to handle this
/*
console.log(alturaHeader);
if (alturaMain < alturaHeader) {
alert("test");
$('.main').css({'min-height': alturaHeader });
}
*/
});
});
--CSS--
.header
{
border:1px solid black;
}
.main
{
border:1px solid red;
height:100%;
}
heigth:100% it will do what u want check the below fiddle
http://jsfiddle.net/7fkp9/
remember as we have border right now so they dont have the same height.. it will very by 2 pixel.. for exact same height dont use the border property or set the border-size to zero(0) pixel

Need Help Getting Floating Social Bar Working

My client is using the "Digg-Digg" plugin on their blog, and has asked me to implement the same thing on the rest of the site. I have copied the html code, the css file & the JS file, updated the links and variables, yet it still won't appear on the page. Can anyone help me out??? Thank you in advance.
Here is the html code:
<a id="dd_end"></a>
<div class='dd_outer'>
<div class='dd_inner'>
<div id='dd_ajax_float' style="position: absolute; top: 308px; left: -95px; display: block;">
<div class='dd_button_v'>
<a href="http://twitter.com/share" class="twitter-share-button" data-url="http://www.scottera.com/" data-count="vertical" data-text="Arch Kit" data-via="archkit" ></a><script type="text/javascript" src="//platform.twitter.com/widgets.js"></script></div><div style='clear:left'></div><div class='dd_button_v'><script src="//connect.facebook.net/en_US/all.js#xfbml=1"></script><fb:like href="http://www.scottera.com" send="false" show_faces="false" layout="box_count" width="50" ></fb:like></div><div style='clear:left'></div><div class='dd_button_v'><script type='text/javascript' src='https://apis.google.com/js/plusone.js'></script><g:plusone size='tall' href='http://www.scottera.com/'></g:plusone></div><div style='clear:left'></div></div></div></div><script type="text/javascript">var dd_offset_from_content = 40;var dd_top_offset_from_content = 0;var dd_override_start_anchor_id = "";var dd_override_top_offset = "";</script><script type="text/javascript" src="include/digg-digg/js/diggdigg-floating-bar.js?ver=5.3.6"></script>
And here is the CSS for the main sections:
.dd_outer {
width:100%;
height:0;
position:absolute;
top:0;
left:0;
z-index:9999
}
.dd_inner {
margin:0 auto;
position:relative
}
EDIT: Adding JS code:
var dd_top = 0;
var dd_left = 0;
jQuery(document).ready(function(){
var $floating_bar = jQuery('#dd_ajax_float');
var dd_anchorId = 'dd_start';
if ( typeof dd_override_start_anchor_id !== 'undefined' && dd_override_start_anchor_id.length > 0 ) {
dd_anchorId = dd_override_start_anchor_id;
}
var $dd_start = jQuery( '#' + dd_anchorId );
var $dd_end = jQuery('#dd_end');
var $dd_outer = jQuery('.dd_outer');
// first, move the floating bar out of the content to avoid position: relative issues
$dd_outer.appendTo('#wrapper');
if ( typeof dd_override_top_offset !== 'undefined' && dd_override_top_offset.length > 0 ) {
dd_top_offset_from_content = parseInt( dd_override_top_offset );
}
dd_top = parseInt($dd_start.offset().top) + dd_top_offset_from_content;
if($dd_end.length){
dd_end = parseInt($dd_end.offset().top);
}
dd_left = -(dd_offset_from_content + 55);
dd_adjust_inner_width();
dd_position_floating_bar(dd_top, dd_left);
$floating_bar.fadeIn('slow');
if($floating_bar.length > 0){
var pullX = $floating_bar.css('margin-left');
jQuery(window).scroll(function () {
var scroll_from_top = jQuery(window).scrollTop() + 30;
var is_fixed = $dd_outer.css('position') == 'fixed';
if($dd_end.length){
var dd_ajax_float_bottom = dd_end - ($floating_bar.height() + 30);
}
if($floating_bar.length > 0)
{
if(scroll_from_top > dd_ajax_float_bottom && $dd_end.length){
dd_position_floating_bar(dd_ajax_float_bottom, dd_left);
$dd_outer.css('position', 'absolute');
}
else if ( scroll_from_top > dd_top && !is_fixed )
{
dd_position_floating_bar(30, dd_left);
$dd_outer.css('position', 'fixed');
}
else if ( scroll_from_top < dd_top && is_fixed )
{
dd_position_floating_bar(dd_top, dd_left);
$dd_outer.css('position', 'absolute');
}
}
});
}
// Load Linked In Sharers (Resolves issue with position on page)
if(jQuery('.dd-linkedin-share').length){
jQuery('.dd-linkedin-share div').each(function(index) {
var $linkedinSharer = jQuery(this);
var linkedinShareURL = $linkedinSharer.attr('data-url');
var linkedinShareCounter = $linkedinSharer.attr('data-counter');
var linkedinShareCode = jQuery('<script>').attr('type', 'unparsed-IN/Share').attr('data-url', linkedinShareURL).attr('data-counter', linkedinShareCounter);
$linkedinSharer.html(linkedinShareCode);
IN.Event.on(IN, "systemReady", function() {
$linkedinSharer.children('script').first().attr('type', 'IN/Share');
IN.parse();
});
});
}
});
jQuery(window).resize(function() {
dd_adjust_inner_width();
});
var dd_is_hidden = false;
var dd_resize_timer;
function dd_adjust_inner_width() {
var $dd_inner = jQuery('.dd_inner');
var $dd_floating_bar = jQuery('#dd_ajax_float')
var width = parseInt(jQuery(window).width() - (jQuery('#dd_start').offset().left * 2));
$dd_inner.width(width);
var dd_should_be_hidden = (((jQuery(window).width() - width)/2) < -dd_left);
var dd_is_hidden = $dd_floating_bar.is(':hidden');
if(dd_should_be_hidden && !dd_is_hidden)
{
clearTimeout(dd_resize_timer);
dd_resize_timer = setTimeout(function(){ jQuery('#dd_ajax_float').fadeOut(); }, -dd_left);
}
else if(!dd_should_be_hidden && dd_is_hidden)
{
clearTimeout(dd_resize_timer);
dd_resize_timer = setTimeout(function(){ jQuery('#dd_ajax_float').fadeIn(); }, -dd_left);
}
}
function dd_position_floating_bar(top, left, position) {
var $floating_bar = jQuery('#dd_ajax_float');
if(top == undefined) top = 0 + dd_top_offset_from_content;;
if(left == undefined) left = 0;
if(position == undefined) position = 'absolute';
$floating_bar.css({
position: position,
top: top + 'px',
left: left + 'px'
});
}
You can use the floating social bar plugin
http://wordpress.org/plugins/floating-social-bar/ (it is my plugin)
There is an option to manually add the floating bar on all WordPress pages if you want. Just look at the code on the FAQ page.

Categories

Resources