Function on resize doesn't work - javascript

Hello I have problem with really easy script. It should change class if under 768 px of window width but it just doesn't work. I have no clue why. I dont want to use media queries in this in this case.
Here's code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>ez</title>
<style>
.aside {
float: left;
height: 1000px;
width: 250px;
background-color: grey;
}
.sidebar {
position: absolute;
top: 0;
left: -250px;
}
</style>
</head>
<body style="height: 2000px">
<aside class="aside" id="aside"></aside>
<main style="float: left; height: 1000px; width: 70%; background-color: black;"></main>
<script>
var elm = document.getElementById("aside");
function change() {
var w = window.innerWidth;
if(w<768) {
elm.className = "sidebar";
} else {
elm.className = "aside";
}
}
window.addEventListener("resize", change);
</script>
</body>
</html>

I started your script. For 768px and more there is class 'aside', for 767px and less class 'sidebar'. So where is the problem?
If you open page on width less than 768 your script won't be working correct. You have to add it to event onload too

Related

Scrollbar height indicator to execute function

I'm using jQuery to get user's current height, and after he reaches that height, there will be animation function (Such as reactive websites, when user scroll down he has animation in different part of the page).
Yet, I can't really figure out why exactly the following code doesn't work.
$(window).scroll(function() {
var height = $(window).scrollTop();
if(height > 200) {
$("#project").animate({
bottom: '250px',
opacity: '0.5',
height: '1000px',
width: '100%'
});
}
});
CSS:
/* About Page */
.about{
width: 100%;
height: 1000px;
background-color: blue;
}
/* Projects Page */
.project{
background-color: red;
}
HTML:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" type="text/css" href="css/style.css" />
<script src="jquery-3.4.1.min.js"></script>
<script src="myscripts.js"></script>
<title>My Portfolio</title>
</head>
<body>
<div id="about" class="about">
</div>
<div id="project" class="project">
</div>
</body>
</html>
How can I use scrolling height indicator to activate functions such as animation?
You need to take into account the height of each section and calculate the scrollBottom position instead, which might be more useful if you want to trigger an animation once you reach some element:
const $about = $('#about');
const $projects = $('#projects');
const $services = $('#services');
// Calculate the top offset of each section (number of sections above it * 1000px each).
// We want to expand them when we are 50px above them, so we substract that.
let projectTop = 1000 - 50;
let servicesTop = 2000 - 50;
$(window).scroll(() => {
requestAnimationFrame(() => {
// Calculate the scrollBottom by summing the viewport's height:
const scrollBottom = $(window).scrollTop() + $(window).height();
if (scrollBottom >= projectTop) {
$projects.animate({ height: '1000px' });
}
if (scrollBottom >= servicesTop) {
$services.animate({ height: '1000px' });
}
});
});
body {
margin: 0;
}
.about {
background: red;
width: 100%;
height: 1000px;
}
.projects {
background: green;
width: 100%;
}
.services {
background: blue;
width: 100%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="about" class="about"></div>
<div id="projects" class="projects"></div>
<div id="services" class="services"></div>

jquery draggable, making a div not to go outside of the other div frame

i need a draggable div not to go outside of second div frame, so far i managed to make a "collision" basically returning true or false if draggable div is inside the frame of other div. So the thing now is that i cant get this to work, i was trying to get it to a x = 90(example) when it hits the frame and few more examples , but i just can't get this to work. The draggable div doesn't want to go back to position.
Here is a JSFiddle: https://jsfiddle.net/kojaa/x80wL1mj/2/
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="style.css">
<title>Catch a ball</title>
</head>
<body>
<div class="catcherMovableArea" id="catcherMovableArea">
<div id="catcher" class="catcher"></div>
</div>
<script src="script.js"></script>
</body>
</html>
.catcherMovableArea {
position: absolute;
border: 1px solid black;
width: 1900px;
top: 90%;
height: 50px;
}
.catcher {
position: absolute;
width: 250px;
height: 30px;
border-radius: 10px;
background-color: black;
top: 20%;
}
let catcher = $("#catcher");
$(document).mousemove(function(e) {
catcher.position({
my: "left-50% bottom+50%",
of: e,
collision: "fit"
});
let catcherOffset = $(catcher).offset();
let CxPos = catcherOffset.left;
let CyPos = catcherOffset.top;
let catcherYInMovableArea, catcherXInMovableArea = true;
while(!isCatcherYinMovableArea(CyPos)){
catcherYInMovableArea = false;
break;
}
while(!isCatcherXinMovableArea(CxPos)){
catcherXInMovableArea = false;
break;
}
});
function isCatcherYinMovableArea(ypos){
if(ypos < 849.5999755859375 || ypos > 870.5999755859375) {
return false;
} else {
return true;
}
}
function isCatcherXinMovableArea(xpos){
if(xpos < 8 || xpos > 1655 ) {
return false;
} else {
return true;
}
}
By default, the collision option will prevent the element from being placed outside of the window. You want to prevent it from moving outside of a specific element.
To do this, use the within option to select which element should be used for containment.
Example:
let draggable = $("#draggable");
$(document).mousemove(function(e) {
draggable.position({
my: "left-50% bottom+50%",
of: e,
collision: "fit",
within: "#container"
});
});
#container { width: 200px; height: 100px; border-style: solid }
#draggable { width: 50px; height: 50px; background-color: black }
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<script src="https://code.jquery.com/ui/1.12.0-rc.1/jquery-ui.js"></script>
<div id="container">
<div id="draggable"></div>
</div>

How to move an drag and drop item to a certain position, when located over canvas?

I am working on a Tablet-environment with draggable objects.
The drag & drop works, it is even possible to drag several objects at once, when implemented.
References are :
Reference 1 & Reference 2
This is how the current version of my code looks like:
<!DOCTYPE html>
<html lang="de">
<head>
<meta charset="utf-8">
<meta
name='viewport'
content='width=50px, initial-scale=1.0, maximum-scale=1.0, user-scalable=0,'
/>
<!--
Refernces:
* https://wiki.selfhtml.org/wiki/JavaScript/Tutorials/Drag_and_Drop
* https://mobiforge.com/design-development/touch-friendly-drag-and-drop
-->
<style>
#container {
width: 200px;
height: 200px;
position: relative;
background: yellow;
top: 100px
}
main1 {
position: relative;
}
div1 {
position: absolute;
top: 0px;
left: 100px;
height: 72px;
width: 72px;
background: red;
border: 0px solid #666;
margin: 0;
padding: 0;
}
</style>
<title>Clean up</title>
</head>
<body>
<div id ="container">
</div>
<main1 id="main1">
<div1 class="draggable" id="d1-0""></div1>
</main1>
<script>
var nodeList = document.getElementsByClassName('draggable');
for(var i=0;i<nodeList.length;i++) {
var obj = nodeList[i];
obj.addEventListener('touchmove', function(event) {
var touch = event.targetTouches[0];
// Place element where the finger is
event.target.style.left = touch.pageX + 'px';
event.target.style.top = touch.pageY + 'px';
event.preventDefault();
}, false);
}
</script>
</body>
</html>
The idea is, that the red box (div1) can be moved, dragged and dropped everywhere on the screen. But it needs to be moved to its very initial starting position, when it enters the yellow canvas. (The idea is to "clean up" and "move objects back to where they came from".)
You should use jQuery UI's draggable and touch punch for mobile friendliness
Let me know if this is close to what you're looking for and we can adjust as needed
$(document).ready(function() {
$('#div1').draggable();
$('#container').droppable({
drop: function( event, ui ) {
alert("You dropped the red on the yellow");
}
});
$(document).on("click", "#animateBtn", function() {
//Simple animate w/ just specifying the offsets
//$('#div1').animate({top:"250px", left:"250px"});
//Other animate options
$('#div1').animate({
top:"15px",
left:"15px"
}, {
duration:555, //Animation time in pixels
easing:"easeOutQuart" //See https://api.jqueryui.com/easings/
});
});
});
#container {
width: 200px;
height: 200px;
position: relative;
background: yellow;
top: 100px
}
body {
position: relative;
}
#div1 {
position: absolute;
top: 0px;
left: 100px;
height: 72px;
width: 72px;
background: red;
border: 0px solid #666;
margin: 0;
padding: 0;
}
#animateBtn {
position:fixed;
right:10px;
bottom:10px;
display:inline-block;
padding:3px 5px;
background-color:green;
color:white;
border-radius:6px
}
<!DOCTYPE html>
<html lang="de">
<head>
<meta charset="utf-8">
<meta
name='viewport'
content='width=50px, initial-scale=1.0, maximum-scale=1.0, user-scalable=0,'
/>
<title>Drag and Drop</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui-touch-punch/0.2.3/jquery.ui.touch-punch.min.js"></script>
</head>
<body>
<div id="container"></div>
<div class="draggable" id="div1"></div>
<div id="animateBtn">Animate</div>
</body>
</html>
<!DOCTYPE html>
<html lang="de">
<head>
<meta charset="utf-8">
<meta
name='viewport'
content='width=50px, initial-scale=1.0, maximum-scale=1.0, user-scalable=0,'
/>
<title>Drag and Drop</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui-touch-punch/0.2.3/jquery.ui.touch-punch.min.js"></script>
<style>
#container {
width: 200px;
height: 200px;
position: relative;
background: yellow;
top: 100px
}
body {
position: relative;
}
#div1 {
position: absolute;
top: 100px;
left: 100px;
height: 72px;
width: 72px;
background: red;
border: 0px solid #666;
margin: 0;
padding: 0;
}
</style>
<title>Clean up</title>
</head>
<body>
<div id="container"></div>
<div class="draggable" id="div1"></div>
<!--<div id="animateBtn">Animate</div>-->
<script>
$(document).ready(function() {
$('#div1').draggable();
$('#container').droppable({
drop: function() {
$('#div1').animate({top:"100px", left:"100px"});
}
});
});
</script>
</body>
</html>
I didn't see a mention of jQuery but w3schools has a working example that goes without. Could you some touchup though:
/**
* Make object draggable
* #param {Element} element
*/
const addDraggable = (element)=> {
let pos1 = 0, pos2 = 0, pos3 = 0, pos4 = 0;
const dragMouseDown = e => {
e = e || window.event;
e.preventDefault();
// get the mouse cursor position at startup:
[pos3, pos4] = [e.clientX, e.clientY];
document.onmouseup = closeDragElement;
document.onmousemove = elementDrag;
};
const elementDrag = e => {
console.log(e.clientX, e.clientY);
e = e || window.event;
e.preventDefault();
// calculate the new cursor position:
[pos1, pos2] = [pos3 - e.clientX, pos4 - e.clientY];
[pos3, pos4] = [e.clientX, e.clientY];
// set the element's new position:
[element.style.top, element.style.left] =
[(element.offsetTop - pos2) + "px", (element.offsetLeft - pos1) + "px"];
};
const closeDragElement = _ => {
// stop moving when mouse button is released:
document.onmouseup = null;
document.onmousemove = null;
};
element.onmousedown = dragMouseDown;
}
document.addEventListener("DOMContentLoaded", event=> {
_('#logo-top').addEventListener('click', event=> {
event.stopPropagation();
_('#logo-top').classList.toggle('active');
_('nav').forEach( n=> n.classList.toggle('collapsed') );
_('main').classList.toggle('extended');
});
addDraggable( _('#help-text') );
_( '#help' ).addEventListener( 'click', ()=>{ _('#help-text').classList.toggle('active')} );
_( '#help-text-close' ).addEventListener( 'click', ()=>{_('#help-text').classList.toggle('active')} );
});
Another way would be to use the Drag Operations

Backwards animation not working properly in Game

I'm trying to make a simple Javascript game which consists in a square expanding, while the player have to hit "A" to make it smaller. The goal is to make the square disappear and not to let the square engulf the whole screen.
But I'm experiencing three issues:
- When I hit A, the square stops expanding and starts getting smaller, but it never stops. It should only work for a about a second and then expand again.
- The pause button (enter) doesn't always work the way it should. I feel like it waits for the animation stop, but I don't want it to work like this.
- The square doesn't expand from the center.
The HTML:
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" href="styles/game.css"></link>
<script language="javascript" type="text/javascript" src="scripts/jquery-1.11.3.min.js"></script>
<script type="text/javascript" src="scripts/game.js"></script>
</head>
<body>
<section class="game">
<div id="game" style="position:absolute;"><img id="player" class="square"></img></div>
</section>
</body>
</html>
The Javascript:
//set update interval
setInterval(update, 10);
var isPlaying = false;
$(document).ready(function() {
});
function playerInput() {
$(document).keydown(function(event) {
if ( event.which == 65 ) {
if (isPlaying == true) {
$("#player").animate({height: '-=10', width: '-=10'}, 1);
}
} else if (event.which == 13) {
isPlaying = !isPlaying;
}
});
}
function update() {
playerInput();
if (isPlaying == true) {
$("#player").animate({height: '+=10', width: '+=10'}, 1);
}
}
The CSS:
body, html {
height: 1000px;
width: 1000px;
margin: auto;
background-color: black;
}
.game {
height: 800px;
width: 800px;
margin: auto;
margin-top: 10px;
background-color: black;
}
.square {
background-image: url("../images/square.png");
margin: 375px;
height: 30px;
width: 30px;
}

Javascript drag and drop on leave doesn't work correctly

I am trying to implement a drag and drop image upload similar functionality to imgur.com.
You drag an image from your desktop and a big overlay div with the word 'upload' appears as you drag over your document.
My problem is that when I drag over the actual word 'upload' inside an h1 tag the screen flickers. This is happening because I have an event for dragleave to remove the overlay div with the upload h1 tag however I don't know how to fix it.
You can see the problem in action here: JS Fiddle, just drag any image from your desktop to the document and hover over the word 'upload' you'll see what I'm talking about. Any help would be appreciated.
HTML:
<!DOCTYPE html>
<html>
<head>
<title>Drag and Drop</title>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
</head>
<body>
<div id="upload-global-drop-overlay" style="display: none;"><h1>upload</h1></div>
</body>
</html>​
Javascript code:
$(document).on('dragover', function () {
$('#upload-global-drop-overlay').css({'display': 'block'});
});
$('#upload-global-drop-overlay').on('dragleave', function () {
$('#upload-global-drop-overlay').css({'display': 'none'});
});
$(document).on('drop', function (e) {
$('#upload-global-drop-overlay').css({'display': 'none'});
e.preventDefault();
});
​
Hey hopefully you found an answer to this, if not here is a little example that looks like imgur in my oppinion, using your code.
jsFiddle: http://jsfiddle.net/JUBwS/74/
HTML:
<!DOCTYPE html>
<html>
<head>
<title>Drag and Drop</title>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
</head>
<body>
<div id="upload-global-drop-overlay" style="display: none;"><h1>upload</h1></div>
</body>
</html>​
CSS:
#upload-global-drop-overlay {
background: none repeat scroll 0 0 #424242;
height: 100%;
width: 100%;
position: fixed;
top: 0;
left: 0;
opacity: .8;
filter: alpha(opacity=80);
-moz-opacity: .8;
z-index: 10001;
display: none;
}
#upload-global-drop-overlay h1 {
font-size: 72pt;
display: block;
position: absolute;
line-height: 50px;
top: 50%;
left: 50%;
margin: -82px 0 0 -180px;
text-shadow: 3px 3px 4px black;
color: white;
z-index: -1;
}​
Javascript:
var isDragging = null;
$(document).on('dragover', function () {
if(isDragging==null)
doDrag();
isDragging = true;
});
$(document).on('drop', function (e) {
e.preventDefault();
isDragging = false;
});
$(document).on('dragleave', function (e) {
isDragging = false;
});
var timerId=0;
function doDrag()
{
timerId = setInterval(function()
{
if(isDragging)
$('#upload-global-drop-overlay').fadeIn(500);
else
{
$('#upload-global-drop-overlay').fadeOut(500);
isDragging = null;
clearInterval(timerId);
}
},200);
}​
This sample uses timers, but it is active only when something is being dragged into the form. I am certainly going to use this in the future.
I actually found another solution, I think it's a bit simpler because it doesn't use setInterval. And I've implemented the actual drag and drop functionality for anyone interested.
The whole working example with drag and drop functionality is available below.
jsFiddle - Demo: http://jsfiddle.net/6SV9P/1/
HTML:
<!DOCTYPE html>
<html>
<head>
<title>Drag and Drop</title>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
</head>
<body>
<div id="upload-global-drop-overlay" style="display: none;"><h1>upload</h1</div>
<div id="image"></div>
</body>
</html>​
CSS:
#upload-global-drop-overlay {
background: none repeat scroll 0 0 #424242;
height: 100%;
width: 100%;
position: fixed;
top: 0;
left: 0;
opacity: .8;
filter: alpha(opacity=80);
-moz-opacity: .8;
z-index: 10001;
display: none;
}
#upload-global-drop-overlay h1 {
font-size: 72pt;
display: block;
position: absolute;
line-height: 50px;
top: 50%;
left: 50%;
margin: -82px 0 0 -180px;
text-shadow: 3px 3px 4px black;
color: white;
z-index: -1;
}​
JS:
var dragDropFromDesktop = (function ($) {
$(document).on('dragenter', function () {
$('#upload-global-drop-overlay').fadeIn(200)
});
$('#upload-global-drop-overlay').on('dragleave', function (e) {
if (e.originalEvent.pageX < 10 || e.originalEvent.pageY < 10 || $(window).width() - e.originalEvent.pageX < 10 || $(window).height - e.originalEvent.pageY < 10) {
$("#upload-global-drop-overlay").fadeOut(200);
}
});
$('#upload-global-drop-overlay').on('dragover', function (e) {
e.stopPropagation();
e.preventDefault();
});
// Handle dropped image file - only Firefox and Google Chrome
$('#upload-global-drop-overlay').on('drop', function (e) {
$('#upload-global-drop-overlay').fadeOut(200);
var files = e.originalEvent.dataTransfer.files;
if (files === undefined) {
alert('Your browser does not support file Drag and Drop!')
} else {
var file = files[0];
if (typeof FileReader !== "undefined" && file.type.indexOf("image") != -1) {
var reader = new FileReader();
reader.onload = function (evt) {
var img = new Image();
img.src = evt.target.result;
$('#image').html('<img src="' + img.src + '">');
};
reader.readAsDataURL(file);
}
}
e.preventDefault();
e.stopPropagation();
});
})(jQuery);​

Categories