how to stop moving text box at specific point? - javascript

i'm developing a web site i want a div to move when a user click on the text box and i need to stop that div below the clicked text box. i have tried
var index = event.target.id
but it didn't work i 'm using flowing javascript function
<script type="text/javascript">
var cmdStr = window.location.search;
cmdStr = (cmdStr.indexOf("menu_id")>-1)?cmdStr.substring(cmdStr.indexOf("=")+1,cmdStr.length):"";
var isNS6 = (navigator.userAgent.indexOf("Mozilla")>-1 && navigator.userAgent.indexOf("Gecko")>-1)?true:false;
var isIE = (navigator.userAgent.indexOf("MSIE")>-1 && navigator.userAgent.indexOf("Opera")==-1)?true:false;
var isOp = (navigator.userAgent.indexOf("Opera")>-1)?true:false;
function init(){
// if(isIE){
// document.getElementById("msg_scroller").style.position="relative";
// }
}
var incrementVal = 2;
var timer;
var flag;
function scroll(flag){
var obj = document.getElementById("movingDiv");
var isIE6 = (document.documentElement.clientHeight)? true : false;`
var Y = parseInt(obj.style.top);
var cY = (isIE6)?document.documentElement.clientHeight-173 :((document.all)? document.body.clientHeight-173:window.innerHeight - 173);
if(flag==1 && Y<cY){
obj.style.top = (Y+incrementVal)+"pt";
timer = setTimeout("scroll(1)",incrementVal*20);
}else if(flag==-1 && Y>0){
obj.style.top = (Y-incrementVal)+"pt";
timer = setTimeout("scroll(-1)",incrementVal*20);
}else{
clearTimeout(timer);
}
}
</script>
and my html is
<div id="movingDiv" style="position:absolute;left:100pt;top:150pt;border:1px;width:160px;background-color:lightyellow;font-weight:bold;" >
<textarea style="font-size: 10pt; font-family: Potha, Malithi Web , Arial Unicode MS;
width: 600px;" rows="7"></textarea>
<text></div>
i know to stop this i have to get x,y cordinates but how i get this ?? can some one help me?

Related

Contact between 2 elements in Javascript or jQuery

guys, I want to ask how could I update x and y coordinate of moving element so when this moving element hits another element it fades out. Thanks for the help in advance.
if ($(element1[counter]).position().top >= $("#element2Id").position().top &&
$(element1[counter]).position().top <= $("#element2Id").position().top + $("#element2Id").height() &&
$(element1[counter]).position().left == $("#element2Id").position().left) {
$("#bubble1Id").fadeOut();
}
counter++;
if (counter == 11)
counter = 0;
You can use the following script that has an improved version of the post I commented on OP see below.
var is_colliding = function($div1, $div2) {
// Div 1 data
var d1_offset = $div1.offset();
var d1_height = $div1.outerHeight(true);
var d1_width = $div1.outerWidth(true);
var d1_distance_from_top = d1_offset.top + d1_height;
var d1_distance_from_left = d1_offset.left + d1_width;
// Div 2 data
var d2_offset = $div2.offset();
var d2_height = $div2.outerHeight(true);
var d2_width = $div2.outerWidth(true);
var d2_distance_from_top = d2_offset.top + d2_height;
var d2_distance_from_left = d2_offset.left + d2_width;
var not_colliding = (d1_distance_from_top < d2_offset.top || d1_offset.top > d2_distance_from_top || d1_distance_from_left < d2_offset.left || d1_offset.left > d2_distance_from_left);
// Return whether it IS colliding
return !not_colliding;
};
you can call it like
var is_colliding = function($div1, $div2) {
// Div 1 data
var d1_offset = $div1.offset();
var d1_height = $div1.outerHeight(true);
var d1_width = $div1.outerWidth(true);
var d1_distance_from_top = d1_offset.top + d1_height;
var d1_distance_from_left = d1_offset.left + d1_width;
// Div 2 data
var d2_offset = $div2.offset();
var d2_height = $div2.outerHeight(true);
var d2_width = $div2.outerWidth(true);
var d2_distance_from_top = d2_offset.top + d2_height;
var d2_distance_from_left = d2_offset.left + d2_width;
var not_colliding = (d1_distance_from_top < d2_offset.top || d1_offset.top > d2_distance_from_top || d1_distance_from_left < d2_offset.left || d1_offset.left > d2_distance_from_left);
// Return whether it IS colliding
return !not_colliding;
};
console.log(is_colliding($("#div1"), $("#div2")));
#div1,
#div2 {
border: 1px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="div1">DIV 1</div>
<div id="div2" style="margin-top:10px;">DIV 2</div>
Change/remove the margin-top to detect collision

getelementbyid().click not working

I am making a website that whenever I click and x is equal to a range of numbers, it plays audio, but after i click once when x is between those numbers, i will also play if x is not in the range. Please Help. Here is my code. by the way, i will not use jquery because it does not work on chrome.
if(x<=1200&&x>=600){
var n=true;
};
if(x<=1200&&x>=600&&n==true){
document.getElementById('a').onclick = function(){
audio.play();
n=false;
}
}
else{n=false}
What your code does is that it adds a click event listener on that element, and afterwards the click handler will trigger regardless of your x value because you don't have any checks inside the click handler.
The solution is to do create the click listener only once, and check for the value of x inside it. Something like this:
document.getElementById('a').onclick = function(){
if(x <= 1200 && x >= 600 && n == true) {
audio.play();
n = false;
}
}
See this (I've replaced audio playing with div highlighting, but it's the same principle):
var r = document.getElementById('r');
var n = true;
var x = 1000;
document.getElementById('a').onclick = function(){
if(x <= 1200 && x >= 600 && n == true) {
r.className = 'playing';
n = false;
printN();
setTimeout(function(){
r.className = '';
}, 2000);
}
}
function toggleN(){n = !n;printN()}
function printN(){document.getElementById('n').textContent = 'n is set to ' + n;}
function randomizeX(){x = Math.floor(Math.random() * 1200);printX()}
function printX(){document.getElementById('x').textContent = 'x equals ' + x;}
#r {display: inline-block; width: 50px; height: 50px; background: #ccc; transition: background 1s linear;}
#r.playing {background: green}
<button id="a">Hit me</button><br><br>
<div id="r"></div>
<p id="x">x equals 1000</p>
<p id="n">n is set to true</p>
<button onclick="toggleN()">Toggle n</button>
<button onclick="randomizeX()">Randomize x</button>
I'm not quite sure what you're trying to do but here a guest :
if(x<=1200&&x>=600){
var n=true;
var clicked = false;
};
if(x<=1200&&x>=600&&n==true || clicked==true){
document.getElementById('a').onclick = function(){
audio.play();
n=false;
clicked = true;
}
}
else{
n=false;
clicked = false;
}
This should do what you want, if i understood you correctly.
no reason to check x several times + check n, since n is only true if x is between your ranges.
var ab = document.getElementById('a');
var n = false;
if( x <= 1200 && x >= 600 ){
n = true; //If x is within range.
} else {
n = false; //Reset when x goes out of range.
}
ab.onclick = function(){
if(n){
audio.play();
}
}
Note: If a user clicks the button several times,
the audio plays several times.
This can be fixed by adding another variable checking if a user already clicked once,
Since i don't know your setup, i.e. should users be able to click to play the audio several times in a row(when it finish playing once), i can't supply you with a solution for that without knowing.

Toggling case on click of a button

I'm having a text area, user can type in the text area, in start it will be lower case, but once user click on the 'T(toggle)' button, what ever typing after that will change to upper case previous one will be in lower case only . If again user click on the 'T(toggle button)' what ever type after that will appear in lower case and so on. I tried but that was not successful.
<input type="button" name="toggleCase" id="toggleCase" value="T" style="width:40px;" onclick="javascript:changeCase(this);" />
<textarea tabindex="1" cols="39" rows="2" onkeydown="checkTxtCase(this);" name="titleText1"> </textarea>
JS:
function checkTxtCase(elmObj) {
setCursorToTextEnd(elmObj.id);
var txtVal = elmObj.value;
var txtLen = txtVal.length;
prevSize = txtLen;
var txtLast = txtVal.substring(txtLen - 1, txtLen);
if (textCase == 'LOWER') {
elmObj.value = txtVal.substring(0, txtLen - 1) + txtLast.toLowerCase();
} else {
elmObj.value = txtVal.substring(0, txtLen - 1) + txtLast.toUpperCase();
}
return true;
}
function setCursorToTextEnd(textControlID) {
var text = document.getElementById(textControlID);
if (text != null && text.value.length > 0) {
if (text.createTextRange) {
var FieldRange = text.createTextRange();
FieldRange.moveStart('character', text.value.length);
FieldRange.collapse();
FieldRange.select();
} else if (text.setSelectionRange) {
var textLength = text.value.length;
text.setSelectionRange(textLength, textLength);
}
}
}
var textCase = 'UPPER';
var prevSize = 0;
function changeCase() {
document.getElementById('titleText1').focus();
textCase = (textCase == 'LOWER') ? 'UPPER' : 'LOWER';
}
Any suggestion is appreciated.
var textCase = 'toLowerCase';
var pos = 0;
function changeCase() {
var textarea = document.getElementsByName('titleText1')[0];
pos = textarea.value.length;
textCase = (textCase == 'toUpperCase') ? 'toLowerCase' : 'toUpperCase';
textarea.focus();
}
function checkTxtCase(elem) {
var l = elem.value.substr(pos);
elem.value = elem.value.substr(0, pos) + l[textCase]();
}
FIDDLE
I have found out a plugin for you. Its really cool and it really works.
http://jquerybyexample.blogspot.com/2011/12/jquery-plugin-for-uppercase-lowercase.html
This will help you
I have created a fiddle for you. Check It
http://jsfiddle.net/KKX5G/2/
$('#Txt').Setcase({caseValue : 'lower'});

Javascript Cursor

I have the following script for a cursor trail, however the cursor image is appearing in the top left corner of the page and is not appearing as the cursor trail? What could be causing the script not to function correctly? I copied this script from: http://www.dynamicdrive.com/dynamicindex13/trailer.htm
I have tried editing the image paths(I originally used absolute paths to the images), I also tried disabling a previously used "plugin" which I was using for this trail
<script>
/******************************************
* Cross browser cursor trailer script- By Brian Caputo (bcaputo#icdc.com)
* Visit Dynamic Drive (http://www.dynamicdrive.com/) for full source code
* Modified Dec 31st, 02' by DD. This notice must stay intact for use
******************************************/
A=document.getElementById
B=document.all;
C=document.layers;
T1=new Array("wp-content/uploads/2012/10/meerkat1.gif",77,39,"wp-content/uploads/2012/07/meerkat2.gif",77,39,"wp-content/uploads/2012/10/meerkat3.gif",77,39,"wp-content/uploads/2012/10/meerkat4.gif",77,39,"wp-content/uploads/2012/10/meerkat5.gif",77,39,"wp-content/uploads/2012/10/meerkat6.gif",77,39)
var offsetx=15 //x offset of trail from mouse pointer
var offsety=10 //y offset of trail from mouse pointer
nos=parseInt(T1.length/3)
rate=50
ie5fix1=0;
ie5fix2=0;
rightedge=B? document.body.clientWidth-T1[1] : window.innerWidth-T1[1]-20
bottomedge=B? document.body.scrollTop+document.body.clientHeight-T1[2] : window.pageYOffset+window.innerHeight-T1[2]
for (i=0;i<nos;i++){
createContainer("CUR"+i,i*10,i*10,i*3+1,i*3+2,"","<img src='"+T1[i*3]+"' width="+T1[(i*3+1)]+" height="+T1[(i*3+2)]+" border=0>")
}
function createContainer(N,Xp,Yp,W,H,At,HT,Op,St){
with (document){
write((!A && !B) ? "<layer id='"+N+"' left="+Xp+" top="+Yp+" width="+W+" height="+H : "<div id='"+N+"'"+" style='position:absolute;left:"+Xp+"; top:"+Yp+"; width:"+W+"; height:"+H+"; ");
if(St){
if (C)
write(" style='");
write(St+";' ")
}
else write((A || B)?"'":"");
write((At)? At+">" : ">");
write((HT) ? HT : "");
if (!Op)
closeContainer(N)
}
}
function closeContainer(){
document.write((A || B)?"</div>":"</layer>")
}
function getXpos(N){
if (A)
return parseInt(document.getElementById(N).style.left)
else if (B)
return parseInt(B[N].style.left)
else
return C[N].left
}
function getYpos(N){
if (A)
return parseInt(document.getElementById(N).style.top)
else if (B)
return parseInt(B[N].style.top)
else
return C[N].top
}
function moveContainer(N,DX,DY){
c=(A)? document.getElementById(N).style : (B)? B[N].style : (C)? C[N] : "";
if (!B){
rightedge=window.innerWidth-T1[1]-20
bottomedge=window.pageYOffset+window.innerHeight-T1[2]
}
c.left=Math.min(rightedge, DX+offsetx);
c.top=Math.min(bottomedge, DY+offsety);
}
function cycle(){
//if (IE5)
if (document.all&&window.print){
ie5fix1=document.body.scrollLeft;
ie5fix2=document.body.scrollTop;
}
for (i=0;i<(nos-1);i++){
moveContainer("CUR"+i,getXpos("CUR"+(i+1)),getYpos("CUR"+(i+1)))
}
}
function newPos(e){
moveContainer("CUR"+(nos-1),(B)?event.clientX+ie5fix1:e.pageX+2,(B)?event.clientY+ie5fix2:e.pageY+2)
}
function getedgesIE(){
rightedge=document.body.clientWidth-T1[1]
bottomedge=document.body.scrollHeight-T1[2]
}
if (B){
window.onload=getedgesIE
window.onresize=getedgesIE
}
if(document.layers)
document.captureEvents(Event.MOUSEMOVE)
document.onmousemove=newPos
setInterval("cycle()",rate)
</script>
This will make an image follow the cursor. I originally used it as a bookmarklet, hence it all being javascript.
var hi = document.createElement("img");
var att = document.createAttribute("src");
var sty = document.createAttribute("style");
var alt = document.createAttribute("onclick");
var ide = document.createAttribute("id");
ide.value = "hi01";alt.value = "alert('Hi')";
att.value = "http://www.picgifs.com/clip-art/cartoons/pokemon/clip-art-pokemon-441770.jpg";
sty.value = "position: absolute;top: 0px;left: 0px;height: 100px;width: 100px;cursor:crosshair;";
hi.setAttributeNode(att);
hi.setAttributeNode(alt);
hi.setAttributeNode(sty);
hi.setAttributeNode(ide);document.body.appendChild(hi);
var scr = document.createElement("script");
var scratt = document.createAttribute("src");
scratt.value = "http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js";
scr.setAttributeNode(scratt);
document.body.appendChild(scr);
$("body").mousemove(function(e){
var a = e.pageX - 50;
var b = e.pageY - 50;
document.getElementById('hi01').style.left = a+'px';
document.getElementById('hi01').style.top = b+'px';
});

Using Javascript to move a div wont work

I have some javascript that should move my div element every 400 milliseconds. From debugging I have found that all my code works except when I go to move the div element. Ie, this code:
block.style.left = xPos[index] + "px";
I am unsure why this code doesn't move my div? Should I use a different method (other than object.style.top etc.) to move my div?
My java script:
<script LANGUAGE="JavaScript" type = "text/javascript">
<!--
var block = null;
var clockStep = null;
var index = 0;
var maxIndex = 6;
var x = 0;
var y = 0;
var timerInterval = 400; // milliseconds
var xPos = null;
var yPos = null;
function moveBlock()
{
//alert( index ); // if you use this you will see my setInterval works fine
if ( index < 0 || index >= maxIndex || block === null || clockStep === null )
{
clearInterval( clockStep );
clockStep = null;
return;
}
block.innerHTML = "yellow"; // this works (just a debug test) so I know block points to the correct HTML element
block.style.left = xPos[index] + "px"; // this doesn't work
block.style.top = yPos[index] + "px";
index++;
}
function onBlockClick( blockID )
{
if ( clockStep !== null )
{
return;
}
block = document.getElementById( blockID );
index = 0;
x = parseInt( block.style.left, 10 );
y = parseInt( block.style.top, 10 );
xPos = new Array( x+10, x+20, x+30, x+40, x+50, x+60 );
yPos = new Array( y-10, y-20, y-30, y-40, y-50, y-60 );
clockStep = setInterval( "moveBlock()", timerInterval );
}
-->
</script>
The value of block.style.left and block.style.top is not set unless you use an absolutely-positioned div with preset values for both left and top (in fact, your array is filled with NaN when I tested). For instance, the code works fine with a div defined like this:
<div id="div1" style="position:absolute;left:100px;top:100px;
width:150px;height:150px;background-color:yellow;"
onclick="onBlockClick(this.id);">
HI
</div>

Categories