spawn div in random position using hover function, Jquery - javascript

I'm trying to make a website containing a div that changes its position to a random location using jquery's hover function. So far, the only way I've gotten it to work is to apply the function to a separate, fixed button that moves the div around when you hover over it.
Why can't I just apply the same javascript function to the div class "rand"?
I'm trying to make a website containing a div that changes its position to a random location using jquery's hover function. So far, the only way I've gotten it to work is to apply the function to a separate, fixed button that moves the div around when you hover over it.
Why can't I just apply the same javascript function to the div class "rand"?
$('.new_pos').hover(function() {
var bodyWidth = document.body.clientWidth
var bodyHeight = document.body.clientHeight;
var randPosX = Math.floor((Math.random() * bodyWidth));
var randPosY = Math.floor((Math.random() * bodyHeight));
var posLog = document.getElementById('pos_log');
var posXY = 'x: ' + randPosX + '<br />' + 'y: ' + randPosY;
$('#rand_pos').css('left', randPosX);
$('#rand_pos').css('top', randPosY);
posLog.innerHTML = posXY
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="rand_pos" class="rand"><img src="Media/MargeDancing_Test01.gif"></div>
<button class="new_pos">Remember</button>
I got the source code from this website: https://codepen.io/kaypooma/pen/tAfwm

The div doesn't have a position property, therefore top and left have no effect.
#rand_pos {
position: relative;
}
https://jsfiddle.net/calder12/54qfvgnm/1
I'd also suggest using mouseover instead of hover, it's a little less flaky on hover
https://jsfiddle.net/calder12/54qfvgnm/2/

Related

Position element in centre of visible viewport window with overflow-y:scroll

I've rather roughly built this website which uses an effect similar to the iOS Safari tab view to look at various pages of a virtual book. Everything is working fine apart from the fact that I can't centre each page in the visible viewport. For example if you scroll down to the final 'page' and click on it, it jumps to the top of the document, instead of staying in the centre of the visible viewport.
I think this is to do with the fact that the scrollable div uses overflow-y:scroll, but I just can't figure out for the life of me how to fix the problem.
Any help would be greatly appreciated!!
Here's my jQuery:
jQuery(document.body).on('click', '.page', function() { //Change to touchstart
// Generate number between 1 + 2
var randomClass = 3;
var randomNumber = Math.round(Math.random() * (randomClass - 1)) + 1;
// Initialise & Random Number
jQuery(this).addClass("activated").addClass('scaled-' + randomNumber);
// Exiting - Reset All
jQuery(document.body).on('click', '.activated', function() { //Change to Touchstart
jQuery(this).removeClass("activated scaled-1 scaled-2 scaled-3");
});
});
And here is a jsfiddle with all my code in it so you can get a better idea of what I'm trying to achieve.
https://jsfiddle.net/ontu1ngq/
Thanks!
You need to get the amount that #wrapper has been scrolled, so that you can use that to set the top of the .page accordingly. Then, when you remove the .activated class, you will just need to remove the inline top style.
jQuery(document.body).on('click', '.page', function() {
var randomClass = 3;
var randomNumber = Math.round(Math.random() * (randomClass - 1)) + 1;
jQuery(this).addClass("activated").addClass('scaled-' + randomNumber);
var wrapper_scrollTop = $("#wrapper").scrollTop(); //gets amount scrolled
var half_wrapper = $("#wrapper").height()*(0.5); //50% of wrapper height
jQuery(this).css("top",half_wrapper+wrapper_scrollTop);
jQuery(document.body).on('click', '.activated', function() {
jQuery(this).removeClass("activated scaled-1 scaled-2 scaled-3");
jQuery(this).css("top","") //returns top to original value specified in css
});
});
Check out this working fiddle: https://jsfiddle.net/tardhepc/1/

Lightbox Centering in jquery

Recently I tried to make the images in lightbox. If you click the image it show off in lightbox effect. But Some of the Reason, Lightbox is not centering properly in a window size. For Example if you click the image it loaded in lightbox but for the first time it lightbox load in bottom of the site and again you click the image it align properly.
here is the screenshot what i exactly saying.
First Screenshot looks when you click the image when page load.
First Time Click the Image:
Second Time Click the Image:
For the First Time it getting alignment problem.
For the Second Time it not getting alignment problem(Without Page Load)
Javascript:
<script>
jQuery(document).ready(function() {
jQuery("img").click(function() {
var img_path;
if ($(this).parent('a').length) {
img_path = $(this).parent('a').prop('href');
}
else
{
img_path = $(this).attr('src');
}
jQuery(".cplightbox1").html(jQuery("<img>").attr("src", img_path));
jQuery(".cpoutter").css('display', 'block');
jQuery('.cpoutter').animate({'opacity': '1'});
//jQuery('.lightbox').animate({'opacity':'1.00'});
var cplightbox = document.getElementsByClassName('cplightbox')[0];
var cpoutter = document.getElementsByClassName('cpoutter')[0];
cplightbox.style.marginTop = ((cpoutter.offsetHeight / 2) - (cplightbox.offsetHeight / 2)) + "px";
return false;
});
});
</script>
HTML CODE:
Here is the Fiddle
http://jsfiddle.net/rCUGD/7/
But Some How this Script is working properly in jsfiddle.net. May Be I messup with script or css
I am Not where i made a mistake
EDITED:
Now After #JustAnil Here is the Screenshot:
After the second click it should show like this normal
Checkout this working JSFiddle.
You need to change the following lines (where you calculate the offset).
Change the following lines:
var cplightbox = document.getElementsByClassName('cplightbox')[0];
var cpoutter = document.getElementsByClassName('cpoutter')[0];
cplightbox.style.marginTop = ((cpoutter.offsetHeight / 2) - (cplightbox.offsetHeight / 2)) + "px";
To:
var cplightbox = document.getElementsByClassName('cplightbox')[0];
// We need the actual height of the image so grab it from the "inner" container
var cplightbox1 = document.getElementsByClassName('cplightbox1')[0]; // New Line
var cpoutter = document.getElementsByClassName('cpoutter')[0];
// Calculate the (negative) offset from the width & height
cplightbox.style.marginLeft = "-"+$(cplightbox1).width() / 2 + "px";
cplightbox.style.marginTop = "-"+$(cplightbox1).height() / 2 + "px";
// ^ Negative offset so we can vertically and horizontally center it.
Finally
Change your CSS from:
.cplightbox {
margin-left: auto;
margin-right:auto;
width:auto;
height:auto;
display:inline-block;
}
To:
.cplightbox {
position:fixed;
top:50%;
left:50%;
display:inline-block;
}
Checkout this question CSS Vertically & Horizontally Center Div (Thats how to center a div to the middle of the screen).
Then alter your javascript to calculate the negative offset (dependant on how big the picture is [ie 50% of the width & height])
View this working JSFiddle.

jQuery Variable Height

I'm trying to have an image gallery where a caption is vertically centered inside of a slideshow, here's the code I'm working with
$(window).load(function() {
var imageHeight = $('.flexslider .slides li img').height();
var captionTop = imageHeight - $('.title-cap').height();
var captionTop = captionTop/2;
$('.title-cap').css('top',captionTop + 'px');
var captionTopOne = imageHeight - $('.sub-cap-one').height();
var captionTopOne = captionTopOne/2;
$('.sub-cap-one').css('top',captionTopOne + 'px');
var captionTopTwo = imageHeight - $('.sub-cap-two').height();
var captionTopTwo = captionTopTwo/2;
$('.sub-cap-two').css('top',captionTopTwo + 'px');
var captionTopThr = imageHeight - $('.sub-cap-three').height();
var captionTopThr = captionTopThr/2;
$('.sub-cap-three').css('top',captionTopThr + 'px');
});
The caption is positioned absolutely, and I'm using top to do the centering...
So my thought process is, get the height of the base slideshow image to keep it responsive, minus the height of the current caption, and divide that by two ending with the top value.
The first instance is working, with "title-cap", but the next three are not. They all return the same wrong value. All caption classes have the same attributes, just different for assignment.
Also, what would I need to add in order for the values to dynamically change with the browser window size in real time.
Edit: Alright, did a little research and figured out the load/resize part.
This is what I have now
function setContent(){
[Added all of the above minus the onload part in here]
}
$(window).load(function() {
setContent();
});
$(window).resize(function() {
setContent();
});
Now just not sure why the sub-cap's aren't loading properly. Any ideas?
I've had similar problem when trying to get the size of hidden elements. I found this nice jQuery actual plugin. It might be what you need.

Detect the percentage of the horizontal position that users click on

I'm trying to make a slider from scratch like the jQuery UI one but i'm not sure how to detect the horizontal position where the user clicks on the slider.
Example, if i click on foo div in the middle, it'd return 50%. If i have that it would be easy for me to adjust the slider's filler div width accordingly.
Try this fiddle: http://jsfiddle.net/UCFtB/1/
Script:
$("#test").mousemove(function(e){
var perc = e.offsetX/ $(this).width() * 100;
$(this).html(e.offsetX + " | " + perc + " perc");
});

CSS: Child div overlapping parent

I have something vaguely like the following:
<div id="body">
surrounding text
<div id="pane" style="overflow: auto; height: 500px; width: 500px;">
lots and lots of text here
<span id="some_bit">tooltip appears below-right of here</span>
</div>
more surrounding text (should be overlapped by tooltip)
</div>
and:
<div id="tooltip" style="width: 100px; height: 100px;">Whee</div>
What I want to do is insert the tooltip such that it is positioned above the pane it's in. If it's attached to an element that's next to the pane boundary (like above), then it should be visible above the pane, and above the text surrounding the pane.
It should NOT a) extend the pane, such that you have to scroll down to see the tooltip (like in http://saizai.com/css_overlap.png), or b) be cut off, so you can't see all of the tooltip.
I'm inserting this with JS, so I can add a wrapper position:relative div or the like if needed, calculate offsets and make it position:absolute, etc. I would prefer to not assume anything about the pane's position property - the tooltip should be insertable with minimal assumptions of possible page layout. (This is just one example case.)
It's for a prototype tooltip library I'm writing that will be open source.
ETA: http://jsfiddle.net/vCb2y/5/ behaves visually like I want (if you keep re-hovering the trigger text), but would require me to update the position of the tooltip on all DOM changes and scrolling behavior. I would rather the tooltip be positioned with pure CSS/HTML so that it has the same visual behavior (i.e. it overlaps all other elements) but stays in its position relative to the target under DOM changes, scrolling, etc.
ETA 2: http://tjkdesign.com/articles/z-index/teach_yourself_how_elements_stack.asp (keep defaults except set cyan div 'a' to position:relative; imagine 'A' is the pane and 'a' the tooltip) seems to more closely behave as I want, but I've not been able to get it to work elsewhere. Note that if you make 'A' overflow: auto, it breaks the overlapping behavior of 'a'.
I can't think of a pure HTML/CSS solution for this.
The overflow declaration is the issue here. If the tooltip is in #pane:
you establish a positioning context within #pane, then the tooltip shows next to #some_bit (regardless of scrolling, etc.) but it gets cut-off.
you do not establish a positioning context, then the tooltip is not clipped but it has no clue where #some_bit is on the page.
I'm afraid you'll need JS to monitor where #some_bit is on the page and position the tooltip accordingly. You'd also need to kill that tooltip as soon as #some_bit is outside of the viewing area (not an issue if the trigger is mouseover).
Actually, if the trigger is mouseover then you may want to use the cursor coordinates to position the tooltip (versus calculating the position of #some_bit).
I would just put the tooltip outside of the #pane div and position it absolutely using JavaScript since you're using JS anyway.
I don't use Prototype so I don't know how it's done in Prototype, but in jQuery, you'd use $(element).position() to get the element position. If you have to do it manually, it's a little more complicated.
And you'll probably want to add a little extra logic to prevent the tooltip from extending outside of the document.
Edit: CSS used
#tooltip {
z-index: 9999;
display: none;
position: absolute;
}
JS used
Note: in jQuery, but it should be easy to change it to Prototype syntax.
$('#some_bit').hover(function() {
var docViewTop = $(window).scrollTop();
var docViewBottom = docViewTop + $(window).height();
// hovered element
var offset = $(this).offset();
var top = offset.top + docViewTop;
var left = offset.left;
var width = $(this).width();
var height = $(this).height();
var right = left + width;
var bottom = top + height;
// pane
var poffset = $('#pane').offset();
var ptop = poffset.top + docViewTop;
var pleft = poffset.left;
var pwidth = $('#pane').width();
var pheight = $('#pane').height();
var pright = pleft + pwidth;
var pbottom = ptop + pheight;
// tooltip
var ttop = bottom;
var tleft = right;
var twidth = $('#tooltip').width();
var theight = $('#tooltip').height();
var tright = tleft + twidth;
var tbottom = ttop + theight;
if (tright > pright)
tleft = pright - twidth;
if (tbottom > pbottom)
ttop = pbottom - theight;
if (tbottom > docViewBottom)
ttop = docViewBottom - theight;
$('#tooltip').offset({top: ttop, left: tleft});
$('#tooltip').css('display', 'block');
}, function() {
$('#tooltip').hide();
});
Edit: See it here.

Categories