I'm trying to make a online map for a game. But I have problems with moving around the map...
This code works only if I set the container (div with map image)
to height: 6000px; and width:6000px;
But I must use height: 100%; width: 100%; to get "background-size: cover;" working to have the map "zoomed out"/"fit to the screen" for the best look imo
$(document).ready(function()
{
var
clicked,
clickY
;
$(document).on(
{
'mousemove': function(e) {clicked && updateScrollPos(e);},
'mousedown': function(e)
{
clicked = true;
clickY = e.pageY;
clickX = e.pageX;
},
'mouseup': function()
{
clicked = false;
$('html').css('cursor', 'auto');
}
});
var updateScrollPos = function(e)
{
$('html').css('cursor', 'all-scroll');
$(window).scrollTop($(window).scrollTop() + (clickY - e.pageY));
$(window).scrollLeft($(window).scrollLeft() + (clickX - e.pageX));
}
});
This is currently how it looks: http://5.231.49.167/map/
Use "google inspect element" to test out what I mean. (Change the 100%'s to 6000px in #container)
The problem is that when you set a 100% height value it take the longitud from the parent container. If the conatiner is the body tag it ajustment to the size of the content it self that could be very samll. You need to set up the size to a specifycally size you can use the window size for example.
Related
im writing a website on which pictures, ordered in a grid, are shown. I want to make it possible to drag them around with the mouse and zoom in and out with the mouse wheel. This already works so far. here is what my code looks like:
var clicked = [0,0];
var pos = [0,0]; // <-- This ist the position of the image(s)
var dragging = false
var zoom = 1;
//this function is for zooming in and out
window.onmousewheel = function(event)
{
if (event.deltaY > 0)
{
zoom *= 0.9;
}
else
{
zoom *= 1.1;
}
update(0, 0);
}
window.onmousedown = function(event)
{
clicked = [event.clientX, event.clientY];
dragging = true;
}
window.onmousemove = function(event)
{
if (dragging == false){return;}
update((event.clientX-clicked[0]),(event.clientY-clicked[1]))
}
window.onmouseup = function(event)
{
pos = [pos[0] + (event.clientX-clicked[0]), pos[1] + (event.clientY-clicked[1])];
dragging = false;
}
function update(addX, addY) //<-- this function just updades the position of the images by using the zoom and pos variable and the addX and addY parameter
All of this works very fine. But it has one Bug: When i'm start draging while the mouse is directly over one of the images, then when i release the mouse the mouseup event is not triggered an so everything is still moving until you click again with your mouse. What i also do not like is that if you are dragging while the mouse is over one of the images, it shows this standard chrome browser image moving thing.
My Idea for solving this problems was, making a div with opacity: 0; in the front over everything, which fits the whole screen. looks like this:
(css)
#controller
{
position:absolute;
top:0;
left:0;
bottom:0;
right:0;
height:100%;
width:100%;
z-index: 999;
opacity: 0;
}
(html)
<div id="controller"></div>
And now it works fine. I also can drag when i start with the mouse direct over an image. But then i realized that now i can not make any click event or an simple css :hover over one of the images anymore, obviously because the invisible div is now in the front :(
Has anyone of you an idea how two solve this problem?
Put the onmouseup inside onmousedown:
window.onmousedown = function(event)
{
clicked = [event.clientX, event.clientY];
dragging = true;
window.onmouseup = function(event)
{
pos = [pos[0] + (event.clientX-clicked[0]), pos[1] + (event.clientY-clicked[1])];
dragging = false;
}
}
Please see my JS Fiddle on both Desktop and iPhone:
https://jsfiddle.net/5jb3x5cn/4/
I am using a click eventListener on document.body:
document.body.addEventListener('click', function(){
alert(1);
})
I filled the background in blue, so that you can see the entire frame is being filled by the body and given it a height of 100vh.
I have inserted one child element for the iPhone.
On desktop, you will notice you get an alert regardless of where you click on the body. On the iPhone, the alert is only displayed when you click on the child element. I can only assume the child element 'fills' the body with some space, where you can click on - regardless of the height the body is set to.
Interestingly enough document.body.clientHeight returns a value which would suggest the body has a decent clickable size.
Now if you head over to: https://jsfiddle.net/5t8arze9/1/
You will notice that the entire body is clickable. Here I have used the touchstart eventListener.
Can anybody point me in the right direction?
Cheers,
Dan
False Code :
document.body.addEventListener('click', function(){
alert(1);
})
True Code :
document.addEventListener("click", function(){
alert(1);
});
you have to change your CSS to really fill the screen. Even the backgroud is blue, you can see that your mouse cursor is not shown correctly.
Add
html, body {
width: 100%;
height: 100%;
margin: 0;
padding: 0;
}
fiddle (update): https://jsfiddle.net/5jb3x5cn/10/
In the end, a colleague this was solved as follows:
Detect iPhone via User-Agent
If iPhone, then combine touchstart, touchmove and touchend eventListeners to determine whether the user just 'clicked' or actually 'swiped'/'scrolled' the screen
If use clicked, open URL, if not - ignore
Non iPhones get the normal click listener set
Code:
if (body.addEventListener) {
if (navigator.userAgent.match(/iPad/i) != null) {
var startX = 0;
var startY = 0;
var endX = 0;
var endY = 0;
body.addEventListener('touchstart', function(event) {
startX = event.touches[0].pageX;
startY = event.touches[0].pageY;
endX = 0;
endY = 0;
}, false);
body.addEventListener('touchmove', function(event) {
endX = event.touches[0].pageX - startX;
endY = event.touches[0].pageY - startY;
}, false);
body.addEventListener('touchend', function(event) {
if (!endX && !endY) {
wallpaperClick(event);
}
startX = 0;
startY = 0;
}, false);
} else {
body.addEventListener("click", function(event) {
wallpaperClick(event);
}, !1);
}
} else {
body.attachEvent("onclick", function(event) {
wallpaperClick(event);
});
}
This however unfortunately does not quite answer why. This is somewhat vaguely explained here:
https://developer.mozilla.org/en-US/docs/Web/Events/click#Safari_Mobile
I'm working on creating a basic heatmap for a site using the following:
$(document).ready(function() {
$(document).on('mousedown', function(evt) {
console.log('X: '+ evt.pageX);
console.log('Y: '+ evt.pageY);
$.post('clickmap.php', {
x:evt.pageX,
y:evt.pageY
});
});
});'
fiddle: http://jsfiddle.net/8jjo7q5y/
Works great, besides when also including click coordinates of a click over an iframe. It appears that this is possible when using CrazyEgg and I've personally tested CrazyEgg by clicking a Google Ad (housed inside an iframe) and the heatmap data returned properly to CrazyEgg.
Any ideas on how to accomplish click tracking an entire page body with iframes included.
HTML:
<div></div>
<iframe src="http://www.jsfiddle.net"></iframe>
CSS:
div {
position: absolute;
width: 300px;
height: 150px;
z-index: 2;
}
iframe {
position: absolute;
width: 300px;
height: 150px;
z-index: 1;
}
JavaScript:
$(window).click(function(e) {
console.log("x:" + e.pageX + ", y:" + e.pageY);
});
FIDDLE http://jsfiddle.net/a9owgqrv/
If the iframe content doesn't need any user interaction at all (clicking, scrolling, etc.), you could place a transparent div on top of it, which would capture the mouse clicks. Otherwise, I think you're out of luck.
(Thanks to #Andranik for showing that the div doesn't actually need transparent (opacity) styling.)
short answer for iframes pointing to different domain without making use of proxys or putting a div over the iframe that causes not to be able to click in the iframe: no
nevertheless here is some bloody attempt
it uses the blur event that gets fired when clicked "outside" of window e.g inside iframe, i added mousemove event to have the coordinates where user clicks into iframe, but this only works once, to work again the user must click outside the iframe and inside again, but its better than nothing ;-)
$(document).ready(function() {
var mouse = {x: 0, y: 0};
document.addEventListener('mousemove', function(e){
mouse.x = e.clientX || e.pageX;
mouse.y = e.clientY || e.pageY
}, false);
$(window).blur( function(e){
console.log("clicked on iframe")
console.log('X: '+ mouse.x);
console.log('Y: '+ mouse.y);
});
$(document).on('mousedown', function(evt) {
console.log('X: '+ evt.pageX);
console.log('Y: '+ evt.pageY);
//$.post('clickmap.php', {
//x:evt.pageX,
//y:evt.pageY
//});
});
});
http://jsfiddle.net/8jjo7q5y/1/
I have an h1 that is far down a page..
<h1 id="scroll-to">TRIGGER EVENT WHEN SCROLLED TO.</h1>
and I want to trigger an alert when the user scrolls to the h1, or has it in it's browser's view.
$('#scroll-to').scroll(function() {
alert('you have scrolled to the h1!');
});
how do I do this?
You can calculate the offset of the element and then compare that with the scroll value like:
$(window).scroll(function() {
var hT = $('#scroll-to').offset().top,
hH = $('#scroll-to').outerHeight(),
wH = $(window).height(),
wS = $(this).scrollTop();
if (wS > (hT+hH-wH)){
console.log('H1 on the view!');
}
});
Check this Demo Fiddle
Updated Demo Fiddle no alert -- instead FadeIn() the element
Updated code to check if the element is inside the viewport or not. Thus this works whether you are scrolling up or down adding some rules to the if statement:
if (wS > (hT+hH-wH) && (hT > wS) && (wS+wH > hT+hH)){
//Do something
}
Demo Fiddle
Combining this question with the best answer from jQuery trigger action when a user scrolls past a certain part of the page
var element_position = $('#scroll-to').offset().top;
$(window).on('scroll', function() {
var y_scroll_pos = window.pageYOffset;
var scroll_pos_test = element_position;
if(y_scroll_pos > scroll_pos_test) {
//do stuff
}
});
UPDATE
I've improved the code so that it will trigger when the element is half way up the screen rather than at the very top. It will also trigger the code if the user hits the bottom of the screen and the function hasn't fired yet.
var element_position = $('#scroll-to').offset().top;
var screen_height = $(window).height();
var activation_offset = 0.5;//determines how far up the the page the element needs to be before triggering the function
var activation_point = element_position - (screen_height * activation_offset);
var max_scroll_height = $('body').height() - screen_height - 5;//-5 for a little bit of buffer
//Does something when user scrolls to it OR
//Does it when user has reached the bottom of the page and hasn't triggered the function yet
$(window).on('scroll', function() {
var y_scroll_pos = window.pageYOffset;
var element_in_view = y_scroll_pos > activation_point;
var has_reached_bottom_of_page = max_scroll_height <= y_scroll_pos && !element_in_view;
if(element_in_view || has_reached_bottom_of_page) {
//Do something
}
});
I think your best bet would be to leverage an existing library that does that very thing:
http://imakewebthings.com/waypoints/
You can add listeners to your elements that will fire off when your element hits the top of the viewport:
$('#scroll-to').waypoint(function() {
alert('you have scrolled to the h1!');
});
For an amazing demo of it in use:
http://tympanus.net/codrops/2013/07/16/on-scroll-header-effects/
Inview library triggered event and works well with jquery 1.8 and higher!
https://github.com/protonet/jquery.inview
$('div').on('inview', function (event, visible) {
if (visible == true) {
// element is now visible in the viewport
} else {
// element has gone out of viewport
}
});
Read this https://remysharp.com/2009/01/26/element-in-view-event-plugin
Fire scroll only once after a successful scroll
Note: By successful scroll I mean when the user has scrolled to the desired
element or in other words when the desired element is in view
The accepted answer worked 90% for me so I had to tweak it a little to actually fire only once.
$(window).on('scroll',function() {
var hT = $('#comment-box-section').offset().top,
hH = $('#comment-box-section').outerHeight(),
wH = $(window).height(),
wS = $(this).scrollTop();
if (wS > ((hT+hH-wH)-500)){
console.log('comment box section arrived! eh');
// This detaches the scroll so doStuff() won't run more than once
$(window).off('scroll');
doStuff();
}
});
You could use this for all devices,
$(document).on('scroll', function() {
if( $(this).scrollTop() >= $('#target_element').position().top ){
do_something();
}
});
Intersection Observer can be the best thing IMO, without any external library it does a really good job.
const options = {
root: null,
threshold: 0.25, // 0 - 1 this work as a trigger.
rootMargin: '150px'
};
const target = document.querySelector('h1#scroll-to');
const observer = new IntersectionObserver(
entries => { // each entry checks if the element is the view or not and if yes trigger the function accordingly
entries.forEach(() => {
alert('you have scrolled to the h1!')
});
}, options);
observer.observe(target);
You can use jQuery plugin with the inview event like this :
jQuery('.your-class-here').one('inview', function (event, visible) {
if (visible == true) {
//Enjoy !
}
});
Link : https://remysharp.com/2009/01/26/element-in-view-event-plugin
This should be what you need.
Javascript:
$(window).scroll(function() {
var hT = $('#circle').offset().top,
hH = $('#circle').outerHeight(),
wH = $(window).height(),
wS = $(this).scrollTop();
console.log((hT - wH), wS);
if (wS > (hT + hH - wH)) {
$('.count').each(function() {
$(this).prop('Counter', 0).animate({
Counter: $(this).text()
}, {
duration: 900,
easing: 'swing',
step: function(now) {
$(this).text(Math.ceil(now));
}
});
}); {
$('.count').removeClass('count').addClass('counted');
};
}
});
CSS:
#circle
{
width: 100px;
height: 100px;
background: blue;
-moz-border-radius: 50px;
-webkit-border-radius: 50px;
border-radius: 50px;
float:left;
margin:5px;
}
.count, .counted
{
line-height: 100px;
color:white;
margin-left:30px;
font-size:25px;
}
#talkbubble {
width: 120px;
height: 80px;
background: green;
position: relative;
-moz-border-radius: 10px;
-webkit-border-radius: 10px;
border-radius: 10px;
float:left;
margin:20px;
}
#talkbubble:before {
content:"";
position: absolute;
right: 100%;
top: 15px;
width: 0;
height: 0;
border-top: 13px solid transparent;
border-right: 20px solid green;
border-bottom: 13px solid transparent;
}
HTML:
<div id="talkbubble"><span class="count">145</span></div>
<div style="clear:both"></div>
<div id="talkbubble"><span class="count">145</span></div>
<div style="clear:both"></div>
<div id="circle"><span class="count">1234</span></div>
Check this bootply:
http://www.bootply.com/atin_agarwal2/cJBywxX5Qp
If you are looking for a javascript version. You can call this method on scroll event listener.
showScrollTop = () =>{
const currentScrollPosition = window.pageYOffset;
let elementID = 'service-selector'
const elementOffsetTop = document.getElementById(elementID).offsetTop
if ( currentScrollPosition > elementOffsetTop){
// place your logic here
} else {
// place your logic here
}
}
window.addEventListener('scroll', showScrollTop)
If you are doing a lot of functionality based on scroll position, Scroll magic (http://scrollmagic.io/) is built entirely for this purpose.
It makes it easy to trigger JS based on when the user reaches certain elements when scrolling. It also integrates with the GSAP animation engine (https://greensock.com/) which is great for parallax scrolling websites
Just a quick modification to DaniP's answer, for anyone dealing with elements that can sometimes extend beyond the bounds of the device's viewport.
Added just a slight conditional - In the case of elements that are bigger than the viewport, the element will be revealed once it's top half has completely filled the viewport.
function elementInView(el) {
// The vertical distance between the top of the page and the top of the element.
var elementOffset = $(el).offset().top;
// The height of the element, including padding and borders.
var elementOuterHeight = $(el).outerHeight();
// Height of the window without margins, padding, borders.
var windowHeight = $(window).height();
// The vertical distance between the top of the page and the top of the viewport.
var scrollOffset = $(this).scrollTop();
if (elementOuterHeight < windowHeight) {
// Element is smaller than viewport.
if (scrollOffset > (elementOffset + elementOuterHeight - windowHeight)) {
// Element is completely inside viewport, reveal the element!
return true;
}
} else {
// Element is larger than the viewport, handle visibility differently.
// Consider it visible as soon as it's top half has filled the viewport.
if (scrollOffset > elementOffset) {
// The top of the viewport has touched the top of the element, reveal the element!
return true;
}
}
return false;
}
I use the same code doing that all the time, so added a simple jquery plugin doing it.
480 bytes long, and fast. Only bound elements analyzed in runtime.
https://www.npmjs.com/package/jquery-on-scrolled-to
It will be
$('#scroll-to').onScrolledTo(0, function() {
alert('you have scrolled to the h1!');
});
or use 0.5 instead of 0 if need to alert when half of the h1 shown.
Quick and fast implementation,
let triggered = false;
$(window).on('scroll',function() {
if (window.scrollY > ($('#scrollTo').offset().top+$('#scrollTo').outerHeight()-window.innerHeight) & !triggered){
console.log('triggered here on scroll..');
triggered = true;
}
});
using global variable triggered = false makes it just to happen once, otherwise, every time crossing past the element, this action is triggered.
I'm trying to create a dragbar so users can stretch the height or width of an element on my page (not interested in using HTML resize).
It seems like I'm pretty close, but I can't figure out why
1) the moveable bar is jumping all over the page
2) the adjustable div is flickering as the size changes (or sometimes disappearing completely).
You can see the demo at http://jsfiddle.net/dYUz7/
Here's the source
var elem = $('.layout');
var resizeBar = $('.resize-bar',elem),
adjustableWrapper = $('.layout-container-wrapper',elem),
posDir = 'Left',
pos = 'X';
if($(elem).hasClass('layout-updown')){
posDir = 'Top';
pos = 'Y';
}
var startPos = resizeBar[0]['offset'+posDir], i = resizeBar[0]['offset'+posDir];
resizeBar.on('mousedown', function(event) {
// Prevent default dragging of selected content
event.preventDefault();
console.log(event);
$(document).on('mousemove', mousemove);
$(document).on('mouseup', mouseup);
});
function mousemove(event) {
i = event['page'+pos] - startPos;
if(pos==='X') return changeSizeWidth(i,event.offsetX);
return changeSizeHeight(i,event.offsetY);
}
function changeSizeWidth(i,width){
resizeBar.css({left : i +'px'});
adjustableWrapper.css({'width': width +'px'});
console.log(adjustableWrapper.css('width'));
}
function changeSizeHeight(i,height){
resizeBar.css({top : i +'px'});
adjustableWrapper.css({'height': height +'px'});
console.log(adjustableWrapper.css('height'));
}
function mouseup() {
$(document).unbind('mousemove', mousemove);
$(document).unbind('mouseup', mouseup);
}
Please don't respond with suggestions for using libraries, I have jQuery in the sample, but I'm using angular in the project, and am trying to not add a bunch of other libraries at this point.
I ended up getting this working by changing the move from the move-bar element to the element which needs to grow or shrink.
The css is a bit messed up, but here's an updated jsfiddle of the result
http://jsfiddle.net/dYUz7/2/
function changeSizeWidth(left){
adjustableWrapper.css({'width': left +'px'});
}