unable to Drag and Drop anywhere on the screen - javascript

I am trying to add drag-drop functionality.I have took reference from this link - Drag-drop fiddle.I have kept all the javascript same have just changed id to my aside and just change the css.But now its not working if I keep the name aside in css it works but chnaging to other class it doesn't work.
css
.divTile {
position: absolute;
left: 0;
top: 0; /* set these so Chrome doesn't return 'auto' from getComputedStyle */
}
javascript
<script>
function drag_start(event) {
var style = window.getComputedStyle(event.target, null);
event.dataTransfer.setData("text/plain",
(parseInt(style.getPropertyValue("left"), 10) - event.clientX) + ',' + (parseInt(style.getPropertyValue("top"), 10) - event.clientY));
}
function drag_over(event) {
event.preventDefault();
return false;
}
function drop(event) {
var offset = event.dataTransfer.getData("text/plain").split(',');
var dm = document.getElementById('divTile');
dm.style.left = (event.clientX + parseInt(offset[0], 10)) + 'px';
dm.style.top = (event.clientY + parseInt(offset[1], 10)) + 'px';
event.preventDefault();
return false;
}
var dm = document.getElementById('divTile');
dm.addEventListener('dragstart', drag_start, false);
document.body.addEventListener('dragover', drag_over, false);
document.body.addEventListener('drop', drop, false);
</script>
html
aside draggable="true" id="divTile">
<div class="col-sm-3">
<section class="panel panel-default ">
<div class="panel">
<span class="thumb pull-left m-t m-l">
<img src="~/Content/images/lef-nav/Pathology.png" class="b-a b-3x b-white">
</span>
<div class="clear m-t">
Pathology
</div>
</div>
</section>
</div>
</aside>

You have used id=divTile in your html but have used it as class in css(.divTile). Just change your css to:
#divTile { //Use #divTile instead of .divTile
position: absolute;
left: 0;
top: 0; /* set these so Chrome doesn't return 'auto' from getComputedStyle */
}
Here is the updated fiddle : "http://jsfiddle.net/kKuqH/2148/"

Related

Add different images when mouse moving in jquery

I'm trying to make a jquery code where you can show different images (1-3 different images) when you move the mouse around.
The images will be right beside the cursor, and they will only appear 1-3, not more than that. And each time the mouse moves, these images will change.
I currently have this as my html code,
<div class="mainbody">
<section class="container">
<div class="img_div">
</div>
</section>
</div>
And my jquery code looks like this:
let img_array = ['./img/awards_icon.png', './img/norinuri_icon.png'];
$("div.mainbody").mousemove(function(e) {
for(i=0; i<img_array.length; i++){
$('.img_div').append("<img src='" + img_array[i] +"'/>");
$('.img_div').fadeIn("5000");
$('.img_div').finish().fadeOut("5000");
$('.img_div').offset({
left: e.pageX,
top: e.pageY + 20
});
}
});
The 2 images that I have in my jquery array appears when the mouse moves, but instead of only having 2 images these images add continuously, without stopping.
So each time I would move my mouse, the images would continue to add infinitely.
I will add more images in the jquery array for sure,
but how should I have only two images added, and change these images as I move the mouse?
Use background-image
var imageArr=["https://www.w3schools.com/css/paper.gif","https://www.w3schools.com/css/gradient_bg.png","https://www.w3schools.com/css/img_tree.png"];
var count=0;
$( ".mainbody" ).mouseover(function() {
$( ".img_div" ).css('background-image', 'url("' + imageArr[count] + '")');
if(count == imageArr.length-1)
count=0;
else
count++;
});
.mainbody{
width: 500px;
height: 500px;
border:1px solid red;
}
.img_div{
width: 200px;
height: 200px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="mainbody">
<section class="container">
<div class="img_div">
</div>
</section>
</div>
Here is working fiddle;
USING mousemove (to avoid the images to change so many times while mouse move I use timeout)
var imageArr=["https://www.w3schools.com/css/paper.gif","https://www.w3schools.com/css/gradient_bg.png","https://www.w3schools.com/css/img_tree.png"];
var count=0;
var timeoutid = 0;
function setImage() {
$( ".img_div" ).css('background-image', 'url("' + imageArr[count] + '")');
if(count == imageArr.length-1)
count=0;
else
count++;
}
$(".mainbody").mousemove(function() {
clearTimeout(timeoutid);
timeoutid = setTimeout(setImage, 100);
});
.mainbody{
width: 500px;
height: 500px;
border:1px solid red;
}
.img_div{
width: 200px;
height: 200px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="mainbody">
<section class="container">
<div class="img_div">
</div>
</section>
</div>
화이팅!
I have created a working example for you. You can try it now:
<div class="mainbody">
<section class="container">
<div class="img_div">
hello
</div>
</section>
css
.mainbody {
border:1px solid red;
display:block;
height:1000px
}
jquery
let img_array = ['https://anotherjavaduke.files.wordpress.com/2018/08/avataaars-2.png',
'https://images2.minutemediacdn.com/image/upload/c_crop,h_1192,w_2121,x_0,y_111/f_auto,q_auto,w_1100/v1554921884/shape/mentalfloss/22461-istock-176984635.jpg'];
$("div.mainbody").on('mousemove', function(e) {
var i;
$('.img_div').html('')
for (i = 0; i < img_array.length; i++) {
console.log($('.img_div').has('img').length)
if ($('.img_div').has('img').length < img_array.length) {
$('.img_div').append("<img style='width:100px; height:100px' src='" + img_array[i] + "'/>");
$('.img_div').fadeIn("5000");
$('.img_div').finish().fadeOut("5000");
$('.img_div').offset({
left: e.pageX,
top: e.pageY + 20
});
}
}
});
Working example
[Codepen] https://codepen.io/prashen/pen/ZEEqJEo

How to set an attribute as percentage in jQuery?

I am unable to set css attribute {left: $numberEquivalentToPercent} in jQuery
var targets = $('.parallax__layer__cell');
var i = 1;
for(i = 1; i <= targets.length; i++)
{
if (targets.parents('.parallax__layer--bg').length) {
//apply to only those element that have a parent having class "parallax__layer--bg"
targets.eq(i).css('left', toString(60*i)+ "%");
}
}
The above code(in JS) is expected to produce the same effect as below(in CSS)
.parallax__layer__cell:nth-child(1) { left: 0%; }
.parallax__layer__cell:nth-child(2) { left: 60%; }
.parallax__layer__cell:nth-child(3) { left: 120%; }
.parallax__layer__cell:nth-child(4) { left: 180%; }
.parallax__layer__cell:nth-child(5) { left: 240%; }
Basically I am trying to convert a static code to dynamic code
What if you put 60 * i into a variable called numPercent and then do numPercent.toString() to convert it to a string?
var targets = $('.parallax__layer__cell');
var i = 1;
for(i = 1; i <= targets.length; i++)
{
if (targets.parents('.parallax__layer--bg').length) {
//apply to only those element that have a parent having class "parallax__layer--bg"
var numPercent = 60*i;
targets.eq(i).css('left', numPercent.toString() + "%");
}
}
Here is working code:
var targets = $('.parallax__layer__cell');
var i ;
for(i = 0; i < targets.length; i++)
{
if (targets.eq(i).parents('div.parallax__layer--bg').length) {
targets.eq(i).css('left', 60*i + "%");
}
}
.parallax__layer__cell{
position:absolute;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrap">
<div class="parallax__layer--bg">
<div class="parallax__layer__cell">a</div>
</div>
<div class="parallax__layer--bg">
<div class="parallax__layer__cell">b</div>
</div>
<div class="parallax__layer--bg">
<div class="parallax__layer__cell">c</div>
</div>
<div class="parallax__layer--bg">
<div class="parallax__layer__cell">d</div>
</div>
<div class="parallax__layer--bg">
<div class="parallax__layer__cell">e</div>
</div>
<div>
<div class="parallax__layer__cell">--no parent--</div>
</div>
</div>
I believe this is a timing issue between parallax script and your script. Since css loads first parallax script works fine. But if you remove css and run your script after parallax script it may not do the same effect. Make sure your script runs before actual parallax script.

Change CSS of inner div when scroll reaches that div

I am attempting to implement a scroll function where the CSS of the inner div's change when it reaches a certain height from the top.
var $container = $(".inner-div");
var containerTop = $container.offset().top;
var documentTop = $(document).scrollTop();
var wHeight = $(window).height();
var minMaskHeight = 0;
var descriptionMax = 200;
var logoMin = -200;
var maskDelta = descriptionMax - minMaskHeight;
var $jobOverview = $container.find(".right");
var $jobLogo = $container.find(".left");
var curPlacementPer = ((containerTop - documentTop) / wHeight) * 100;
var topMax = 85;
var center = 20;
var bottomMax = -15;
//console.log("Placement: " + curPlacementPer);
function applyChanges(perOpen) {
var maskHeightChange = maskDelta * (perOpen / 100);
var opacityPer = perOpen / 100;
var newDescriptionLeft = descriptionMax - maskHeightChange;
var newLogoLeft = logoMin + maskHeightChange;
if (newDescriptionLeft <= 0) newDescriptionLeft = 0;
if (newLogoLeft >= 0) newLogoLeft = 0;
if (opacityPer >= 1) opacityPer = 1;
$jobOverview.css({
transform: "translate(" + newDescriptionLeft + "%,-50%)",
opacity: opacityPer
});
$jobLogo.css({
transform: "translate(" + newLogoLeft + "%,-50%)",
opacity: opacityPer
});
}
if (window.innerWidth > 640) {
$container.removeClass("mobile");
// console.log("Placement: " + curPlacementPer);
if (curPlacementPer <= topMax /*&& curPlacementPer >= center*/ ) {
var perOpen = ((topMax - curPlacementPer) / 25) * 100;
applyChanges(perOpen);
} else if (curPlacementPer < center /*&& curPlacementPer >= bottomMax*/ ) {
var perOpen = (((bottomMax - curPlacementPer) * -1) / 25) * 100;
applyChanges(perOpen);
} else {
$jobOverview.css({
transform: "translate(200%,-50%)",
opacity: "0"
});
$jobLogo.css({
transform: "translate(-300%,-50%)",
opacity: "0"
});
}
<div class="outer-div">
<div class="inner-div first">
<div class="left"></div>
<div class="right"></div>
</div>
<div class="inner-div second">
<div class="left"></div>
<div class="right"></div>
</div>
<div class="inner-div third">
<div class="left"></div>
<div class="right"></div>
</div>
<div class="inner-div fourth">
<div class="left"></div>
<div class="right"></div>
</div>
</div>
Currently, all of the inner div's gets changed at the same time.
I noticed that when I change the $container class to equal '.first' and specify it more, it works.
Is there any way to make the inner div's change separately, relative to its height from the top? Any way I can iterate the scroll function so I can add more inner div's in the future and not have to worry about changing my scroll function?
In raw JavaScript, this is my answer:
// Define the element -- The '#fooBar' can be changed to anything else.
var element = document.querySelector("#fooBar");
// Define how much of the element is shown before something happens.
var scrollClipHeight = 0 /* Whatever number value you want... */;
// Function to change an element's CSS when it is scrolled in.
const doSomething = function doSomething() {
/** When the window vertical scroll position plus the
* window's inner height has reached the
* top position of your element.
*/
if (
(window.innerHeight + window.scrollY) - (scrollClipHeight || 0) >=
element.getBoundingClientRect().top
)
// Generally, something is meant to happen here.
element.style = "/* Yay, some CSS! */"
};
// Call the function without an event occurring.
doSomething();
// Call the function when the 'window' scrolls.
addEventListener("scroll", doSomething, false)
This is the method I use. If there are other methods, I'd love to see them as well but this is my answer for now.
consider using 3rd party jQuery plugin for easier job, like one of these:
https://github.com/xobotyi/jquery.viewport
or
https://github.com/zeusdeux/isInViewport
then you can have additional element selector e.g.: ":in-viewport"
so you can:
$(window).on('scroll',function() {
$('div').not(':in-viewport').html('');
$('div:in-viewport').html('hello');
});
Check if current scroll offset from top is bigger than the element offset from the top:
$(window).scroll(function() {
var height = $(window).scrollTop();
var element = $('#changethis'); //change this to your element you want to add the css to
if(height > element.offset().top) {
element.addClass('black'); //add css class black (change according to own css)
}
});
Html:
<div id="changethis">Test</div>
Css:
body
{
height:2000px;
}
.black
{
background-color:black;
color:white;
padding:20px;
}
Demo:
https://codepen.io/anon/pen/WZdEap
You could easily implement this in your existing code.
Below is the sample snippet code, Hope it'll work for you:
$(document).ready(function(){
topMax = 100;
topMin = 25;
$(document).scroll(function(){
$('.inner-div').each(function(){
if($(this).offset().top-$(window).scrollTop()<=topMax && $(this).offset().top-$(window).scrollTop()>=topMin){
$(this).css({'background':'#c7c7c7'});
}else{
$(this).css({'background':'inherit'});
}
});
});
});
div{
width:100%;
border:1px solid red;
padding:5px;
}
div.inner-div{
border: 1px dashed green;
height: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="outer-div">
<div class="inner-div first">
<div class="left"></div>
<div class="right"></div>
</div>
<div class="inner-div second">
<div class="left"></div>
<div class="right"></div>
</div>
<div class="inner-div third">
<div class="left"></div>
<div class="right"></div>
</div>
<div class="inner-div fourth">
<div class="left"></div>
<div class="right"></div>
</div>
</div>
Happy to help you! :)

jquery : Text on moving div (infinite wall)

I need to make an infinite wall which will pull text from database and show it on the wall. I have written this code -
$(function() {
var x = 0;
var y = 100.0;
var z=0;
setInterval(function() {
x -= 0.1;
y -= 0.1;
z++;
if (x <= -100.0){
$("#h1d1").html("loop div 1 :" + z);
x = 0;
}
if (y <= 0){
$("#h1d2").html("loop div 2 :" + z);
y = 100.0;
}
$('#movimg1').css('left', x + "%");
$('#movimg2').css('left', y + "%");
}, 10);
$("#stopbutton").click(function() {
$('#movimg1').stop();
});
})
But the text are not behaving as I wanted it to behave. It changes in the middle of the screen which I don't want. I need the text to change when it is out of view.
https://jsfiddle.net/oa0wdxcx/2/
A couple more things- I want to add a play/pause button. Any advice on how I could achieve that would be much appreciated. Also I want the divs to be inside #wrap div, but if I change the position attribute to relative, the divs don't remain together.
Thanks in advance.
The problem was in the conditions.
if (x <= -100.0) {
z++;
$("#h1d1").html("loop div 1 :" + z);
x = 100; /* change this line */
}
if (y <= -100.0) { /* change this line */
w++;
$("#h1d2").html("loop div 2 :" + w);
y = 100;
}
the conditions says that if any of these two divs reaches left:-100% then the element must place at the end of queue at left:100%.
And one other thing you can combine these if statements and only use x to do the transition.
For start and stop button to work, you should kill the simulation to stop by using clearInterval() function, and call doSimulate() to start again:
var started = true;
$("#stopbutton").click(function () {
if(started) {
clearInterval(sim);
$(this).html('Start');
started = false;
}else{
doSimulate();
$(this).html('Stop');
started = true;
}
});
Here is jsFiddle With Start/Stop Working.
Look at this JSFiddle, i added one more to get a smooth transition back to start.. The third should contain same message as first.
HTML
<body>
<div class="row">
<div class="col-xs-1"></div>
<div id="wrap" class="col-xs-10">
<div class="movimg message1" id="movimg1">
<h1 class="header">start div 1</h1>
</div>
<div class="movimg message2" id="movimg2">
<h1 class="header">start div 2</h2>
</div>
<div class="movimg message1" id="movimg3">
<h1 class="header">start div 1</h1>
</div>
</div>
<div class="col-xs-1"></div>
</div>
<div class="row">
<button class="button" id="startbutton" style="display:none;">Start</button>
<button class="button" id="stopbutton">Stop</button>
</div>
</body>
JavaScript
$(function () {
var x = 200.0;
var interval;
function start(){
interval = setInterval(function () {
x -= 0.1;
if (x <= 0.0) {
x = 200;
}
$('#movimg1').css('left', (x-200) + "%");
$('#movimg2').css('left', (x-100) + "%");
$('#movimg3').css('left', x + "%");
}, 10);
}
start();
$("#stopbutton").click(function () {
window.clearInterval(interval);
$(this).hide();
$("#startbutton").show();
});
$("#startbutton").click(function () {
start();
$(this).hide();
$("#stopbutton").show();
});
})
CSS
body {
overflow: hidden;
}
#wrap {
width: 80%;
left: 10%;
}
.movimg{
position: absolute;
height: 600px;
width: 100%;
background-image: url('https://s-media-cache-ak0.pinimg.com/736x/89/ed/e5/89ede56bcc8243787e55676ab28f287f.jpg');
}
#movimg1 {
left: 0%;
}
#movimg2 {
left: 100%;
}
#movimg3 {
left: 200%;
}
.header {
text-align: center;
}
.button{
top: 600px;
position: relative;
}
UPDATE
Now with Stop and Start buttons: JSFiddle

Make dynamic div elements collapse like collapsable headers

I'm looking to achieve something like this demo here, but for each element of a class, it will stop scrolling and drag the next div up from the bottom. This could be a similar thing to a printer printing paper. I'm not sure how it will fully work for the JS side but what I have is below. I'm close, but it doesn't like doing more than 2 elements. Adding the support for the extra elements would be amazing because then this could be released as a library to achieve the effect.
If the below snippet doesn't look like it works quite right view it here on codepen.
$(document).ready(function() {
$('.container:first-child').css('position', 'relative');
});
$(window).scroll(function() {
$('.container').each(function(i) {
var winheight = $(window).scrollTop() + $(window).height();
var distToTop = $(this).position().top + $(this).height();
var dist = distToTop - winheight;
if ((dist) <= 0) {
$(this).css('position', 'fixed').css('top', ($(this).children().height() - $(window).height()) / (-2) + 'px');
} else if (dist == $(this).height()) {
$(this).css('position', 'relative').css('top', $(window).height() + 'px').css('z-index','1');
}
console.log(dist + ' ' + i);
});
});
body {
margin: 0;
padding: 0;
}
.container {
position: fixed;
top: 100%;
}
.container:first-child {
background: tan;
width: 100%;
height: 100%;
}
.container:nth-child(2) {
background: blue;
width: 100%;
height: 100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class='big'>
<div class='container'>
<div class='t'>
<img src='http://placehold.it/500x250'>
<img src='http://placehold.it/500x250'>
</div>
</div>
<div class='container'>
<div class='t2'>
<img src='http://placehold.it/500x250/fff'>
<img src='http://placehold.it/500x250/fff'>
</div>
</div>
<div class='container'>
<div class='t'>
<img src='http://placehold.it/500x250'>
<img src='http://placehold.it/500x250'>
</div>
</div>
<div class='container'>
<div class='t2'>
<img src='http://placehold.it/500x250/fff'>
<img src='http://placehold.it/500x250/fff'>
</div>
</div>
</div>
The Demo on this site is currently a little wonky because of the difference in windows sizes.

Categories