Function to move an image when image is clicked? - javascript

I have an html file called index.html, and it has this div in there
<body>
<div id="rock"> <img src="rock.PNG" alt="rock" onclick="test()"> </div>
<div id="paper"> <img src="paper.PNG" alt="rock"></div>
<div id="scissors"> <img src="scissors.PNG" alt="rock"> </div>
test is my function, and its within the same file and its written here
<script type="text/javascript">
function test(){
var elem = document.getElementById("rock");
var pos = 0;
var id = setInterval(frame, 10);
function frame() {
if (pos == 350) {
clearInterval(id);
} else {
pos++;
elem.style.top = pos + 'px';
elem.style.left = pos + 'px';
}
}
}
</script>
but when my page runs I click the image, and it does not move. the image is displayed, and the onclick does work (i tested it with alert) but the image won't move... any ideas?

You need to specify the position attribute, likely relative. You could also use absolute or fixed positioning if one of those fits your needs better.
#rock, #paper, #scissors {
position: relative;
}

You need a relative position to be able to change top,bottom,left,right properties
<div id="rock" style="position: relative;">
<img src="rock.PNG" alt="rock" onclick="test()">
</div>

Have you tried change the position of the elements?
https://www.w3schools.com/css/css_positioning.asp
Ex:
<body>
<div id="rock" onclick="test()" style="position:absolute;"> <img src="teste.PNG" alt="rock" > </div>
</body>
<script type="text/javascript">
var pos = 0;
var elem = null;
var id = null;
function test() {
console.log("test");
elem = document.getElementById("rock");
id = setInterval(frame, 10);
}
function frame() {
console.log("frame");
if (pos == 350) {
clearInterval(id);
} else {
pos++;
elem.style.top = pos + 'px';
elem.style.left = pos + 'px';
}
}
</script>

Related

function doesn't work on button (myMove is not defined at HTMLButtonElement.onclick)

This is my html:
<template>
<div id="app">
<div id="myContainer">
<div id="nav">
<router-link to="/">Home</router-link> |
<router-link to="/about">About</router-link>
</div>
<router-view />
<button onclick="myMove()">Test</button>
<img id="picture" :src="randomImage" />
</div>
</div>
</template>
my function myMove() doesn't work on click and i don't understand why, should be an animation(picture should go down from the top) do you have some solution guys?
one more thing, JavaScript:
function myMove() {
const elem = document.getElementById("picture");
let pos = 0;
let id = setInterval(frame, 10);
function frame() {
if (pos == 350) {
clearInterval(id);
} else {
pos++;
elem.style.top = pos + "px";
elem.style.left = pos + "px";
}
}
}
and one more thing, i am using vue-cli
maybe problem is some how connected with that or for example i am using ESlint and everything should be ES6, maybe i didn't use some needed conditions?
Waiting for your answer,thank you!
You need to change the position property of your <img> element to either relative or absolute.
The default is static and will keep your image in place.
<img id="picture" :src="randomImage" style="position:relative" />

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! :)

Javascript - if the width of an element is 100%, do something

How do I force javascript to do the following?
If the width of an element with the id myBar is 100%, change the style of an element with the ID result to be "block" (it's set to none)?
Please answer!
Code: html
<div id="myProgress">
<div id="myBar"></div>
</div>
<button onclick="move()">Run Malware Code Scan</button>
<p id="result">
<em>Fount 142 threats!</em> Take responsibility please!
</p>
Code: CSS
#myProgress {
width: 100%;
background-color: #ebf442;
}
#myBar {
width: 1%;
height: 30px;
background-color: #ed4949;
}
#result {display:none;}
ul li {list-style-type:square;}
Code: JS
<script>
function move() {
var elem = document.getElementById("myBar");
var width = 1;
var id = setInterval(frame, 3);
function frame() {
if (width >= 100) {
clearInterval(id);
} else {
width++;
elem.style.width = width + '%';
}
}
}
</script>
<script>
if (document.getElementById("myBar").style.width= "100%")
document.getElementById("result").style.display ="block"
</script>
P.S.: I'm a beginner at JS!
Edit
You can change display to block in your frame function when you check if width is >= 100. Wouldn't that solve your problem?
<script>
function move() {
var elem = document.getElementById("myBar");
var width = 1;
var id = setInterval(frame, 3);
function frame() {
if (width >= 100) {
clearInterval(id);
document.getElementById("result").style.display = "block";
} else {
width++;
elem.style.width = width + '%';
}
}
}
</script>
The problem of style properties
The element.style.property returns no value until the css is applied from the tag i.e <div style="..."></div>.
So your code is not working. You should apply the width css from the tag to make your code work.
<div id="myProgress">
<div id="myBar" style="width: 100%;"></div>
</div>
<button onclick="move()">Run Malware Code Scan</button>
<p id="result">
<em>Fount 142 threats!</em> Take responsibility please!
</p>
As Oen44 figured out, there is a syntax error too in your if condition (== is written as =).

unable to Drag and Drop anywhere on the screen

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/"

How do I stop clicking next too many times from breaking my image rotator?

Im new to jquery and have been trying to code a simple image rotator, it works well at the moment except for the fact that if you click the "next" of "prev" buttons too many times very quickly it will break the image rotator.
Here is the html:
<div id="viewport">
<div id="imageContainer">
<div class="image" style="background-color:red;">
<div class="title"><p>This is the title of the post</p></div>
</div>
<div class="image" style="background-color:green;">
<div class="title"><p>This is the title of the post</p></div>
</div>
<div class="image" style="background-color:yellow;">
<div class="title"><p>This is the title of the post</p></div>
</div>
<div class="image" style="background-color:brown;">
<div class="title"><p>This is the title of the post</p></div>
</div>
<div class="image" style="background-color:purple;">
<div class="title"><p>This is the title of the post</p></div>
</div>
</div>
</div>
<input type="button" name="prev" id="prev" value="prev" />
<input type="button" name="next" id="next" value="next" />
and jquery:
var ic = $('#imageContainer');
var numItems = $('.image').size();
var position = 0;
ic.css('left', '0px');
var inter;
var rotateTimeout;
function rotate(){
inter = setInterval(function(){
if (position == (numItems - 1)) {
console.log(position);
$('.image').first().insertAfter($('.image').last());
ic.css('left', '+=400px');
position--;
}
ic.animate({opacity: 0.2, left: "-=400px"}, 1500, function(){
ic.animate({opacity: 1.0}, 1000);
});
position += 1;
}, 6000);
}
rotate();
$('#prev').click(function () {
console.log(position);
if (position == 0) {
$('.image').last().insertBefore($('.image').first());
ic.css('left', '-=400px');
position++;
}
ic.animate({
left: "+=400px"
});
position -= 1;
clearInterval(inter);
clearTimeout(rotateTimeout);
rotateTimeout = setTimeout(rotate, 10000);
});
$('#next').click(function () {
if (position == (numItems - 1)) {
console.log(position);
$('.image').first().insertAfter($('.image').last());
ic.css('left', '-400px');
position--;
}
ic.animate({
left: "-=400px"
});
position += 1;
clearInterval(inter);
clearTimeout(rotateTimeout);
rotateTimeout = setTimeout(rotate, 10000);
});
Here is a demo of the rotator.
So how can I either stop the user from clicking the button too quickly, or perhaps only account for a click per two seconds to allow the rotator to do what it needs?
To limit function call frequency you can use some "Throttle" function. For example _.throttle from Underscore.js or any other implementation. It is not necessary to use whole library, only required function could be copied from there.
The event handler attachment will look like this:
$('#prev').click( _.throttle(function () { yours code... }, 2000) );

Categories