jquery check if img is inside div - javascript

// w a s d
$(document).ready(function(e){
var keys = {};
$(document).keydown(function(event){
keys[event.which] = true;
}).keyup(function(event){
delete keys[event.which];
});
var $d = $("img");
function gameLoop() {
if (keys[68]) {
$d.css("left", function(i,oldVal) { return parseInt(oldVal) + 5 + "px"; });
}
else if (keys[65]) {
$d.css("left", function(i,oldVal) { return parseInt(oldVal) - 5 + "px"; });
}
if (keys[83]) {
$d.css("top", function(i,oldVal) { return parseInt(oldVal) + 5 + "px"; });
}
else if (keys[87]) {
$d.css("top", function(i,oldVal) { return parseInt(oldVal) - 5 + "px"; });
}
setTimeout(gameLoop, 20);
}
gameLoop();
$(document).focus();
});
// arrows
$(document).ready(function(e){
var keys = {};
$(document).keydown(function(event){
keys[event.which] = true;
}).keyup(function(event){
delete keys[event.which];
});
var $d = $("img");
function gameLoop() {
if (keys[37]) {
$d.css("left", function(i,oldVal) { return parseInt(oldVal) - 5 + "px"; });
}
else if (keys[39]) {
$d.css("left", function(i,oldVal) { return parseInt(oldVal) + 5 + "px"; });
}
if (keys[40]) {
$d.css("top", function(i,oldVal) { return parseInt(oldVal) + 5 + "px"; });
}
else if (keys[38]) {
$d.css("top", function(i,oldVal) { return parseInt(oldVal) - 5 + "px"; });
}
setTimeout(gameLoop, 20);
}
gameLoop();
$(document).focus();
});
$(document).ready(function(){
if($(".goal:has(img)")){
alert("yes");
}
});
img {
position : absolute;
left: 0;
top: 0;
}
.goal{
width: 10px;
height: 10px;
background-color: green;
float: right;
}
<!DOCTYPE html>
<html>
<head>
<title>Super Mario!</title>
<link rel='stylesheet' type='text/css' href='style.css'/>
</head>
<body>
<img src="http://i1061.photobucket.com/albums/t480/ericqweinstein/mario.jpg"/>
<div class="goal"></div>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<script src="script.js"></script>
</html>
I want an alert box that pops up when the Mario(img) is inside the goal(div). Thanks for the help. don't mind my js code it's just something random and I don't know if it's close to right, Thanks!
Edit: the div is the green dot on the top right corner.

Try with $(".goal").find("img").length > 0
$(document).ready(function() {
if ($(".goal").find("img").length > 0) {
alert("yes");
} else { alert( "no" ); }
});
img {
position: absolute;
left: 0;
top: 0;
}
.goal {
width: 10px;
height: 10px;
background-color: green;
float: right;
}
<!DOCTYPE html>
<html>
<head>
<title>Super Mario!</title>
<link rel='stylesheet' type='text/css' href='style.css' />
</head>
<body>
<img src="http://i1061.photobucket.com/albums/t480/ericqweinstein/mario.jpg" />
<div class="goal"></div>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<script src="script.js"></script>
</html>

I want an alert box that pops up when the Mario(img) is inside the
goal(div).
It seems, that you don't need to check if the element img is inside the div or not. What you want to do is just check if the coordinates of your mario img are within the range of the goal div.
Easiest would be to use element.getBoundingClientRect, to obtain the DOMRect object which will hold the size and position of your elements. Use this to figure out if your mario is in the range of your goal.
Create a function to check the position every time keyboard navigation happens. Like this:
function checkMario() {
var goalPost = $('.goal')[0].getBoundingClientRect();
var mario = $('#mario')[0].getBoundingClientRect();
if ((goalPost.left - mario.left) < 60) {
$('#result').text('yesssss');
} else {
$('#result').text('no yet');
}
}
Example Snippet:
In this example, I have kept it simple to simply calculate if the left position is within the range of the div. You will then need to refine it further to check for all sides.
Try using your keyboard left/right keys to move the mario in to the goal.
$(document).ready(function(e) {
var keys = {};
$(document).keydown(function(event) {
keys[event.which] = true;
}).keyup(function(event) {
delete keys[event.which];
});
var $d = $("img");
function gameLoop() {
if (keys[68]) {
$d.css("left", function(i, oldVal) {
return parseInt(oldVal) + 5 + "px";
});
} else if (keys[65]) {
$d.css("left", function(i, oldVal) {
return parseInt(oldVal) - 5 + "px";
});
}
if (keys[83]) {
$d.css("top", function(i, oldVal) {
return parseInt(oldVal) + 5 + "px";
});
} else if (keys[87]) {
$d.css("top", function(i, oldVal) {
return parseInt(oldVal) - 5 + "px";
});
}
setTimeout(gameLoop, 20);
}
gameLoop();
$(document).focus();
});
// arrows
$(document).ready(function(e) {
var keys = {};
$(document).keydown(function(event) {
keys[event.which] = true;
}).keyup(function(event) {
delete keys[event.which];
});
var $d = $("img");
function gameLoop() {
if (keys[37]) {
$d.css("left", function(i, oldVal) {
return parseInt(oldVal) - 5 + "px";
});
checkMario();
} else if (keys[39]) {
$d.css("left", function(i, oldVal) {
return parseInt(oldVal) + 5 + "px";
});
checkMario();
}
if (keys[40]) {
$d.css("top", function(i, oldVal) {
return parseInt(oldVal) + 5 + "px";
});
checkMario();
} else if (keys[38]) {
$d.css("top", function(i, oldVal) {
return parseInt(oldVal) - 5 + "px";
});
checkMario();
}
setTimeout(gameLoop, 20);
}
gameLoop();
$(document).focus();
});
function checkMario() {
var goalPost = $('.goal')[0].getBoundingClientRect();
var mario = $('#mario')[0].getBoundingClientRect();
if ((goalPost.left - mario.left) < 60) {
$('#result').text('yesssss');
} else {
$('#result').text('no yet');
}
}
img {
position: absolute;
left: 0; top: 0; width: 60px;
}
.goal {
width: 10px; height: 10px;
background-color: green; float: right;
}
p { margin-top: 64px; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<img id='mario' src="http://i1061.photobucket.com/albums/t480/ericqweinstein/mario.jpg" />
<div class="goal"></div>
<br/>
<p id="result"></p>

Your question have 2 cases.
Image inside of div at any level, children and it's children too. In that case,
if ($(".goal").find('img').length) {
// yes
}
If you want to check only children and not children of children you can try
if($(.goal).find('> img').length) {
// yes
}

Change your selector and check the length of the result: $(".goal img").length
$(document).ready(function() {
if ($(".goal img").length) {
alert("yes");
}
});
img {
position: absolute;
left: 0;
top: 0;
}
.goal {
width: 10px;
height: 10px;
background-color: green;
float: right;
}
<!DOCTYPE html>
<html>
<head>
<title>Super Mario!</title>
<link rel='stylesheet' type='text/css' href='style.css' />
</head>
<body>
<img src="http://i1061.photobucket.com/albums/t480/ericqweinstein/mario.jpg" />
<div class="goal">
<img>
</div>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<script src="script.js"></script>
</html>

try this
$(document).ready(function(){
if($("img").closest('.goal').length){
alert("yes");
}
});

Check for image tag length using find .
$(document).ready(function(){
if ($('.goal').find('img').length >0 )
alert("yes");
else
alert("no");
});
img {
position : absolute;
left: 0;
top: 0;
}
.goal{
width: 10px;
height: 10px;
background-color: green;
float: right;
}
<!DOCTYPE html>
<html>
<head>
<title>Super Mario!</title>
<link rel='stylesheet' type='text/css' href='style.css'/>
</head>
<body>
<img src="http://i1061.photobucket.com/albums/t480/ericqweinstein/mario.jpg"/>
<div class="goal"></div>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<script src="script.js"></script>
</html>

Related

jQuery: Nesting letter transform function

This is the code:
$(document).ready(function() {
var isRandom = false;
$('#one, #two').html(function(i, html) {
var chars = $.trim(html).split("");
return '<span>' + chars.join('</span><span>') + '</span>';
});
$('#one').click(function() {
isRandom = !isRandom;
if (isRandom) {
$('span').each(function() {
$(this).css({
"position": "absolute"
});
$(this).animate({
left: Math.random() * window.outerWidth / 2,
top: Math.random() * window.outerHeight / 2,
});
});
} else {
$('span').each(function() {
$(this).css({
"position": "relative"
});
$(this).animate({
left: 0,
top: 0,
});
});
}
});
});
html,
body {
width: 100%;
height: 100%;
}
div {
font-family: Arial;
font-size: 20px;
text-transform: uppercase;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="one">Click me</div>
<div id="two">Flying letters based on #one</div>
<div>No flying letters</div>
If you click the first div, the letters from #one and #two start moving. That's exactly how it should look like. But then: If you want to get the previous state, you would need have to click a letter from #once. It also should work if you click one of the two other div.
How is it possible to do that? Would be happy if somebody could help me!
You can add click event on #two to do that as below -
$('#two').click(function() {
if (isRandom) {
isRandom = false;
$('span').each(function() {
$(this).css({
"position": "relative"
});
$(this).animate({
left: 0,
top: 0,
});
});
}
});
Final code (I have extracted into functions for better understanding) -
$(document).ready(function() {
var isRandom = false;
$('#one, #two').html(function(i, html) {
var chars = $.trim(html).split("");
return '<span>' + chars.join('</span><span>') + '</span>';
});
$('#one').click(function() {
isRandom = !isRandom;
if (isRandom) {
fly();
} else {
restore();
}
});
$('#two').click(function() {
if (isRandom) {
isRandom = false;
restore();
}
});
function fly() {
$('span').each(function() {
$(this).css({
"position": "absolute"
});
$(this).animate({
left: Math.random() * window.outerWidth / 2,
top: Math.random() * window.outerHeight / 2,
});
});
}
function restore() {
$('span').each(function() {
$(this).css({
"position": "relative"
});
$(this).animate({
left: 0,
top: 0,
});
});
}
});
html,
body {
width: 100%;
height: 100%;
}
div {
font-family: Arial;
font-size: 20px;
text-transform: uppercase;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="one">Click me</div>
<div id="two">Flying letters based on #one</div>
<div>No flying letters</div>
You can simply change your selector to some class which is same to all divs then inside event handler you just need to check if the div which is clicked has id has one using && if yes then only if part will get executed .
Demo Code :
$(document).ready(function() {
var isRandom = false;
$('#one, #two').html(function(i, html) {
var chars = $.trim(html).split("");
return '<span>' + chars.join('</span><span>') + '</span>';
});
//chnage slector
$('div.sameclass').click(function() {
isRandom = !isRandom;
//check if the div which is clicked has id one..
if (isRandom && $(this).attr("id") == "one") {
$('span').each(function() {
$(this).css({
"position": "absolute"
});
$(this).animate({
left: Math.random() * window.outerWidth / 2,
top: Math.random() * window.outerHeight / 2,
});
});
} else {
$('span').each(function() {
$(this).css({
"position": "relative"
});
$(this).animate({
left: 0,
top: 0,
});
});
}
});
});
html,
body {
width: 100%;
height: 100%;
}
div {
font-family: Arial;
font-size: 20px;
text-transform: uppercase;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="one" class="sameclass">Click me</div>
<div id="two" class="sameclass">Flying letters based on #one</div>
<div class="sameclass">No flying letters</div>

Div ID changed on screen load but new id script not triggering on click

I am trying to get a randomised winner popup.
I have gotten to the point where when the page loads, one of the 3 divs id's is replaced by winner.
The issue is when clicking the div with the id winner, it does not trigger the jquery associated with it.
Is there anything I can change to fix this issue?
A sample of the code I am using is included below.
<script>
$(document).ready(function(){
$("#left").click(function(){
$("#limg").attr('src', 'https://via.placeholder.com/175');
});
$("#center").click(function(){
$("#cimg").attr('src', 'https://via.placeholder.com/175');
});
$("#right").click(function(){
$("#rimg").attr('src', 'https://via.placeholder.com/175');
});
$("#winner").click(function(){
$("#wimg").attr('src', 'https://via.placeholder.com/190');
$("#winbox").css('display','block');
$("#winbox").css('z-index','2');
});
});
</script>
<style>
#winbox {display:none; background-color:red; color:white; padding:20px;}
</style>
<body>
<div id="winbox">WINNER</div>
<div id="left"><img id="limg" src="https://via.placeholder.com/145"></div>
<div id="center"><img id="cimg" src="https://via.placeholder.com/150"></div>
<div id="right"><img id="rimg" src="https://via.placeholder.com/155"></div>
<script>
window.onload = function() {
var selector = Math.floor(Math.random() * 3) + 1;
if (selector == 1) document.getElementById("left").id = ("winner"), document.getElementById("limg").id = ("wimg");
else if (selector == 2) document.getElementById("center").id = ("winner"), document.getElementById("cimg").id = ("wimg");
else if (selector == 3) document.getElementById("right").id = ("winner"), document.getElementById("rimg").id = ("wimg");
}
</script>
</body>
Moved
$("#winner").click(function() {
$("#wimg").attr('src', 'https://via.placeholder.com/190');
$("#winbox").css('display', 'block');
$("#winbox").css('z-index', '2');
to run after random div selection instead of page load.
$(document).ready(function() {
$("#left").click(function() {
$("#limg").attr('src', 'https://via.placeholder.com/175');
});
$("#center").click(function() {
$("#cimg").attr('src', 'https://via.placeholder.com/175');
});
$("#right").click(function() {
$("#rimg").attr('src', 'https://via.placeholder.com/175');
});
});
#winbox {
display: none;
background-color: red;
color: white;
padding: 20px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>
<div id="winbox">WINNER</div>
<div id="left"><img id="limg" src="https://via.placeholder.com/145"></div>
<div id="center"><img id="cimg" src="https://via.placeholder.com/150"></div>
<div id="right"><img id="rimg" src="https://via.placeholder.com/155"></div>
<script>
window.onload = function() {
var selector = Math.floor(Math.random() * 3) + 1;
console.log(selector)
if (selector == 1) document.getElementById("left").id = ("winner"), document.getElementById("limg").id = ("wimg");
else if (selector == 2) document.getElementById("center").id = ("winner"), document.getElementById("cimg").id = ("wimg");
else if (selector == 3) document.getElementById("right").id = ("winner"), document.getElementById("rimg").id = ("wimg");
$("#winner").click(function() {
$("#wimg").attr('src', 'https://via.placeholder.com/190');
$("#winbox").css('display', 'block');
$("#winbox").css('z-index', '2');
});
}
</script>
</body>

Error moving aside element when created at runtime

Im trying to create a program for one of my games(details not needed) nevertheless I can move around aside elements written in the code
<aside draggable="true" class="dragme" data-item="0">One</aside>
but if I create it at runtime(via button click) it gives me this error in the console
Uncaught TypeError: Cannot read property 'style' of undefined
Here is my full code anybody have ideas?
<!DOCTYPE HTML>
<html>
<head>
<style>
aside {
position: absolute;
left: 0;
top: 0;
width: 200px;
background: rgba(255, 255, 255, 1);
border: 2px solid rgba(0, 0, 0, 1);
border-radius: 4px;
padding: 8px;
}
.second {
left: 100px;
top: 100px;
}
body, html {
min-height: 100vh;
}
body{
width:700px;
height:700px;
}
</style>
</head>
<body ondragover="drag_over(event)" ondrop="drop(event)">
<div class="ControlPanel">
<button onclick="CreateNew('item1')">Item1</button>
</div>
<aside draggable="true" class="dragme" data-item="0">One</aside>
<script>
var dataNum = 0;
function CreateNew(item){
if(item == "item1"){
dataNum += 1;
var asi = document.createElement("ASIDE");
asi.setAttribute("draggable",true);
asi.setAttribute("class","dragme second");
asi.setAttribute("data-item",dataNum);
asi.setAttribute("style","left: 347px; top: 82px;");
document.body.appendChild(asi);
}
}
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) + ',' + event.target.getAttribute('data-item'));
}
function drag_over(event) {
event.preventDefault();
return false;
}
function drop(event) {
var offset = event.dataTransfer.getData("text/plain").split(',');
var dm = document.getElementsByClassName('dragme');
dm[parseInt(offset[2])].style.left = (event.clientX + parseInt(offset[0], 10)) + 'px';
dm[parseInt(offset[2])].style.top = (event.clientY + parseInt(offset[1], 10)) + 'px';
event.preventDefault();
return false;
}
var dm = document.getElementsByClassName('dragme');
for (var i = 0; i < dm.length; i++) {
dm[i].addEventListener('dragstart', drag_start, false);
document.body.addEventListener('dragover', drag_over, false);
document.body.addEventListener('drop', drop, false);
}
</script>
</body>
</html>
You are registering the event listener only once during the page load. Therefore, when you create a new element, you need to re-register the events for the newly created elements too.
<script>
var dataNum = 0;
function CreateNew(item){
if(item == "item1"){
dataNum += 1;
var asi = document.createElement("ASIDE");
asi.setAttribute("draggable",true);
asi.setAttribute("class","dragme second");
asi.setAttribute("data-item",dataNum);
asi.setAttribute("style","left: 347px; top: 82px;");
document.body.appendChild(asi);
registerDragMe(); // --> Add this
}
}
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) + ',' + event.target.getAttribute('data-item'));
}
function drag_over(event) {
event.preventDefault();
return false;
}
function drop(event) {
var offset = event.dataTransfer.getData("text/plain").split(',');
var dm = document.getElementsByClassName('dragme');
dm[parseInt(offset[2])].style.left = (event.clientX + parseInt(offset[0], 10)) + 'px';
dm[parseInt(offset[2])].style.top = (event.clientY + parseInt(offset[1], 10)) + 'px';
event.preventDefault();
return false;
}
// create a wrapper function
function registerDragMe(){
var dm = document.getElementsByClassName('dragme');
for (var i = 0; i < dm.length; i++) {
dm[i].addEventListener('dragstart', drag_start, false);
document.body.addEventListener('dragover', drag_over, false);
document.body.addEventListener('drop', drop, false);
}
}
registerDragMe();
</script>
Working example : https://jsfiddle.net/jcLjr70y/

simple animation in java script

I'm trying to learn Java Script Animations and I found really good examples on this site: http://javascript.info/tutorial/animation#maths-the-function-of-progress-delta
But the problem is, as a beginner, I don't understand how the functions and objects work with each other.
Question 01
I copied the example "Let’s create a movement animation on it’s base:" But my version does not work.
<!DOCTYPE HTML>
<html>
<head>
<style>
.example_path{
position: relative;
width: 600px;
height: 100px;
border-style: solid;
border-width: 5px;
}
.example_block{
position: absolute;
width: 100px;
height: 100px;
background-color: yellow;
}
</style>
</head>
<body>
<div onclick="move(this.children[0])" class="example_path">
<div class="example_block"></div>
</div>
<script>
function move(element, delta, duration) {
var to = 500
animate({
delay: 10,
duration: duration || 1000, // 1 sec by default
delta: delta,
step: function(delta) {
element.style.left = to*delta + "px"
}
})
}
</script>
</body>
</html>
output console: ReferenceError: animate is not defined
Does anyone know what the problem is?
Question 02
My second wish is, to integrate the easeInOut function
function makeEaseInOut(delta) {
return function(progress) {
if (progress < .5)
return delta(2*progress) / 2
else
return (2 - delta(2*(1-progress))) / 2
}
}
bounceEaseInOut = makeEaseInOut(bounce)
How can I link both code snippets? The code is also from this page: http://javascript.info/tutorial/animation#maths-the-function-of-progress-delta
Add animate and makeEaseInOut into your script tag then you can use them. You may want to include the functions in a separate JavaScript file eventually.
<script>
function animate(opts) {
var start = new Date
var id = setInterval(function() {
var timePassed = new Date - start
var progress = timePassed / opts.duration
if (progress > 1) progress = 1
var delta = opts.delta(progress)
opts.step(delta)
if (progress == 1) {
clearInterval(id)
}
}, opts.delay || 10)
}
function makeEaseInOut(delta) {
return function(progress) {
if (progress < .5)
return delta(2*progress) / 2
else
return (2 - delta(2*(1-progress))) / 2
}
}
bounceEaseInOut = makeEaseInOut(bounce)
</script>
that's what I tried.
I still have problems.
output console: delta is not a function. bounce is not a function.
I know I have to learn more about creating functions. But right now I'm not that good to solve the problem.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<style>
.example_path{
position: relative;
width: 600px;
height: 100px;
border-style: solid;
border-width: 5px;
}
.example_block{
position: absolute;
width: 100px;
height: 100px;
background-color: yellow;
}
</style>
<script>
function move(element, delta, duration) {
var to = 500;
animate({
delay: 10,
duration: duration || 1000, // 1 sec by default
delta: delta,
step: function(delta) {
element.style.left = to*delta + "px"
}
});
}
function animate(opts) {
var start = new Date;
var id = setInterval(function() {
var timePassed = new Date - start;
var progress = timePassed / opts.duration;
if (progress > 1) progress = 1
var delta = opts.delta(progress);
opts.step(delta);
if (progress == 1) {
clearInterval(id);
}
}, opts.delay || 10);
}
function makeEaseInOut(delta) {
return function(progress) {
if (progress < .5)
return delta(2*progress)/2;
else
return (2 - delta(2*(1-progress)))/2;
};
}
varbounceEaseInOut = makeEaseInOut(bounce);
</script>
</head>
<body>
<div onclick="move(this.children[0], makeEaseInOut(bounce), 3000)" class="example_path">
<div class="example_block"></div>
</div>
</body>
</html>
I've made a very simple animation using javascript, hope it helps, try to "Run code snippet" for better understanding.
/*JavaScript*/
function myMove() {
var elem = document.getElementById("animate");
var pos = 0;
var id = setInterval(frame, 5);
function frame() {
if (pos == 350) {
clearInterval(id);
} else {
pos++;
elem.style.top = pos + 'px';
elem.style.left = pos + 'px';
}
}
}
function Back() {
var elem1 = document.getElementById("animate");
var id1 = setInterval(frame2, 5);
var pos1 = 350;
function frame2() {
if (pos1 == 0) {
clearInterval(id1);
} else {
pos1--;
elem1.style.top = pos1 + 'px';
elem1.style.left = pos1 + 'px';
}
}
}
/*CSS*/
#container {
width: 400px;
height: 400px;
position: relative;
background: yellow;
}
#animate {
width: 50px;
height: 50px;
position: absolute;
background-color: red;
}
/*HTML*/
<button onclick="myMove()">Click Me</button>
<button onclick="Back()"> roll back</button>
<div id ="container">
<div id ="animate"></div>
</div>

If/else statements not functioning

I cannot figure out why if/else statements are not executing properly. The code only runs through the if(i===1) loop but thats it. I'm doing a simple exercise wherein I check the number submitted and see if the users gets hotter or colder to a preset number.
<html>
<head>
<title>Test</title>
<script src="jquery-1.11.0.min.js"></script>
<script>
$(document).ready(function () {
var checkNum = Math.floor(Math.random() * 10);
alert("Random number is" + checkNum);
var i = 0;
var scopedVal;
var submitVal;
var hotCheck = function (submitVal) {
if(i === 1) {
alert("try again");
scopedVal = submitVal;
alert("scopedVal is" + scopedVal);
} else {
if(abs(scopedVal - checkNum) > abs(submitVal - checkNum)) {
alert("Hotter");
scopedVal = submitVal;
} else {
alert("colder");
scopedVal = submitVal;
}
}
};
$('.subm').on('click', function () {
i++;
alert(" i is" + i);
alert("button pressed");
submitVal = $(this).closest('#outsideContainer').find('.num').val();
if(submitVal === checkNum) {
alert("You got it");
} else {
hotCheck(submitVal);
}
});
});
</script>
<style>
body {
width: 900px;
color: white;
margin: auto;
}
#outsideContainer {
width: 400px;
color: grey;
margin: auto;
position: relative;
}
</style>
</head>
<body>
<div id="outsideContainer">
<form>
<input type="text" name="text" class="num">
<br/>
</form>
<div id="buttonSubm">
<button class="subm">Submit</button>
<div></div>
</body>
</html>
I'm assuming this is a simple fix and it is driving me nuts.
If you want to run the "else" code as well as the "if" code remove the else statement:
var hotCheck = function(submitVal){
if(i===1){
console.log("try again");
scopedVal = submitVal;
console.log("scopedVal is " + scopedVal);
};
if(Math.abs(scopedVal-checkNum)> Math.abs(submitVal - checkNum)){
console.log("Hotter");
scopedVal = submitVal;
} else {
console.log("colder");
scopedVal = submitVal;
};
};
Demo:
http://jsfiddle.net/hHC88/
You also needed to change abs. to Math.abs
The abs() method does not exist. You're dealing with all integers so you can probably just remove it or fully reference it Math.abs()
You have to replace the
if( abs(scopedVal-checkNum)> abs(submitVal - checkNum)){
to
if( Math.abs(scopedVal-checkNum) > Math.abs(submitVal - checkNum)){
abs() is a method to Math.
Try this

Categories

Resources