How to use multiple javascript events in one HTML doc? - javascript

I have a page with 2 javascript events, one triggered from the mouse, the other from the keyboard. When I load the page I can get one or the other to work, but not both. If I press a key first that function will run, but then I cannot do the mouse click or another keystroke. And vice versa. I know jQuery makes this easier, but I'd rather not have my users download that for each page, so I'm trying to do this the old fashioned way. I have read as much about javascript events as I can find but I'm stuck here with this one ...
thanks in advance, Brad.
NOTE: in Chrome and Safari I get the above results, Firefox and Opera will only work with the keystroke function
<html>
<head>
<script>
function create(event) {
var x=event.clientX-14;
var y=event.clientY-33;
var output = document.write("<p id=\"text\" style=\"background-color: white; position: absolute; top:" + y + "px;left:" + x + "px;\";>You're Text, your M#jesty!</p>");
}
function type(event)
{
var letter_in = event.keyCode;
var letter = String.fromCharCode(letter_in);
//var shift = event.shiftKey;
//if (shift === false) {letter = String.toLowerCase;}
document.write(letter);
}
</script>
</head>
<body onmousedown="create(event)" onkeydown="type(event)">
</body>
</html>

It's because you're using document.write() which clears everything else on the page, including your handlers.
Calling document.write() after the document has been loaded implicitly calls document.open(), which clears the document.
So to fix this, you want to use something like innerHTML to only update the contents of an element within your page.
See this example:
<html>
<head>
</head>
<body onmousedown="create(event)" onkeydown="type(event)">
<div id="foo"></div>
<script>
function create(event) {
var x=event.clientX-14;
var y=event.clientY-33;
var output = document.getElementById("foo").innerHTML = "<p id=\"text\" style=\"background-color: white; position: absolute; top:" + y + "px;left:" + x + "px;\";>You're Text, your M#jesty!</p>";
}
function type(event)
{
var letter_in = event.keyCode;
var letter = String.fromCharCode(letter_in);
//var shift = event.shiftKey;
//if (shift === false) {letter = String.toLowerCase;}
document.getElementById("foo").innerHTML = letter;
}
</script>
</body>
</html>

Related

where is showing conversation value

THis topic is abouton google add word (conversation)
Below is my conversation setup screenshot
http://nimb.ws/alycTQ
Below is my code that was putted on body tag
<script type="text/javascript">
/* <![CDATA[ */
function GoogleFormTracker()
{
goog_snippet_vars = function() {
var w = window;
w.google_conversion_id = 949468534;
w.google_conversion_label = "9xLwCK7rm3IQ9vrexAM";
w.google_conversion_value = 1;
w.google_remarketing_only = false;
}
// DO NOT CHANGE THE CODE BELOW.
goog_report_conversion = function(url) {
goog_snippet_vars();
window.google_conversion_format = "3";
var opt = new Object();
opt.onload_callback = function() {
if (typeof(url) != 'undefined') {
window.location = url;
}
}
var conv_handler = window['google_trackConversion'];
if (typeof(conv_handler) == 'function') {
conv_handler(opt);
}
}
}
/* ]]> */
</script>
<script type="text/javascript"
src="//www.googleadservices.com/pagead/conversion_async.js">
</script>
GoogleFormTracker() fired on footer when site is load.
And also i verified my code on tag manager chrome addons(No error showing there).
but i don't know where to showing me how many time this function is fired ?
let me know any mistake in my code or where is showing tracking value in add word (with screenshot and step by step).
Thanks
In google add word account follow below step
Tool->Attribution
In Attribution available you conversation value.
I hope u need like above
"but i don't know where to showing me how many time this function is fired". Not entirely sure I understand, but perhaps you just need to put a console.log('marco'); inside the function and view the browser console (ctrl + shift + i) to see how many times the function is called?

What code is required to swap a javascript variable (trailimage) to another when clicking within a website

When clicking (onmousedown or onclick) for example, I would like to change the variable of the trailimge in the javascript to another image. You see, I have an image (a hand) that is following the cursor coordinates. I am unable to code and change the current image to swap to another trailimage after clicking. I will also need to find a way of reverting to the original trailimage when unclicking. The affect will seem as though the handis tapping or pointing.
var trailimage=["images/contact/gardening-glove-cursor.png", , ]
I believe the answer may be within some form of swap variable scripting
e.g.
var a = 1,
b = 2;
var foo = 1;
var bar = 2;
foo = [bar, bar = foo][0];
Trailimage javascript excerpts
var trailimage=["images/contact/gardening-glove-cursor.png", , ]
var offsetfrommouse=[-110,5]
var displayduration=0
if (document.getElementById || document.all)
document.write('<div id="trailimageid" style="position:absolute;visibility:visible;left:0px;top:100px;width:1px;height:1px"><img border="0" src="'+trailimage[0]+'"></div>')
function followmouse(e){
var xcoord=offsetfrommouse[0]
var ycoord=offsetfrommouse[1]
if (typeof e != "undefined"){
xcoord+=e.pageX
ycoord+=e.pageY
}
</script>
Try this
Fiddle
var trailimage = ["http://img2.wikia.nocookie.net/__cb20130626213446/elderscrolls/images/2/2d/TES3_Morrowind_-_Glove_-_Black_Left_Glove.png",
"http://img2.wikia.nocookie.net/__cb20130626213454/elderscrolls/images/9/91/TES3_Morrowind_-_Glove_-_Black_Right_Glove.png"]
$(function() {
$(".logo").attr("src",trailimage[0]);
$(document).mousemove(function(e) {
$('.logo').offset({
left: e.pageX,
top: e.pageY + 20
});
});
$(document).on("mousedown",function() {
$(".logo").attr("src",trailimage[1]);
})
$(document).on("mouseup",function() {
$(".logo").attr("src",trailimage[0]);
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<img class="logo" src="//ssl.gstatic.com/images/logos/google_logo_41.png" alt="glove" />
Possible Duplicate How do I change the style of the cursor with JQuery?
you can specify like
$('#trailimageid').css('cursor', 'url(' + trailimage[i] + ')');
assuming i as array index

How can I make something move in javascript?

I made a div and a button. Made a function on button's click that set div's margin (i.e move it). But how can I make it move on every click. Whenever I hit the button it do moves, (without refreshing the page) when I press that button again it don't work? How to make it move on every click of button! Here's my code:-
<!DOCTYPE html>
<html>
<head>
<title>JavaScript</title>
<style>
body
{
font-family:ebrima;
}
</style>
</head>
<body onload="" id="demo">
<div name="player" style="float:right; height:32px; width:32px; background:green;" id="myDiv"></div>
<form name="myForm" method="post">
<button value="MOVE" type="button" name="moveButton" onClick="move()">MOVE</button>
</form>
<script>
function move()
{
document.getElementById("myDiv").style.margin="0px 10px 0px 0px";
}
</script>
</body>
</html>
Use a variable to set the new margin each time. After using it, change the variable's value so that next time, it will move somewhere else.
var x = 10;
function move() {
document.getElementById("myDiv").style.margin="0px "+x+"px 0px 0px";
x = x+10;
}
First, don't use inline js (like onclick). Read some of these results: *Why is inline js bad?*
Instead, attach your event listener with javascript:
var myBtn = document.getElementById('my-btn');
myBtn.addEventListener('click', move);
Your code would be more readable/efficient and easier to debug like this:
//cache element reference in advance
var document.getElementById("myDiv")
function move() {
//just target the property you want to change.
myDiv.style.marginLeft = x+'px';
x = x+10;
}
Here's a little demo (click) I put together you may enjoy.
var myDiv = document.getElementById('my-div');
var myBtn = document.getElementById('my-btn');
myBtn.addEventListener('click', move);
function move(e) {
var v = r()+'px '+r()+'px '+r()+'px '+r()+'px';
myDiv.style.margin = v;
}
function r() {
return getRandomInt(0, 20);
}
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1) + min);
}
And here's a more fun one using mousemove rather than click. Demo here.
I would advise using jQuery, which makes a lot of javascript quite simple.
Here's a sample jQuery animation for you:
<script>
function move() {
$("#myDiv").animate({left:'+=250px'});
}
</script>
This will shift the button over by 250px every time you trigger the function.
Note that you'll need to add jQuery to your project (which is trivial). The jQuery website has some well organized tutorials that should help you find your way around JavaScript and jQuery - happy coding!
Like this:
function move() {
var elt = document.getElementById("myDiv"),
currentMargin = parseInt(elt.style.marginRight, 10);
elt.style.marginRight = currentMargin + 10 + 'px';
}

popup in a popup, second popup has no focus?

Ok I know this is going to sound weird but it is what the client wants. I am working within a popup and when a user clicks on a datagrid cell within a certain column it will popup a html table with data. I have the second popup to display but it does not get focus. This is currently the code I am using to create the second popup. Any help to get the focus on this second popup would be great.
function onCellClick() {
var cmGrid = igtbl_getGridById("countermeasureDetailsGrid");
var cmCellID = cmGrid.ActiveCell.split("_");
if (cmCellID[3] === "3") {
var countermeasureID = igtbl_getCellById("countermeasureDetailsGrid_rc_" + cmCellID[2] + "_0").getValue();
var recordType = igtbl_getCellById("countermeasureDetailsGrid_rc_" + cmCellID[2] + "_4").getValue();
_crfPopupWindow = new crfPopupWindow(countermeasureID, recordType);
_crfPopupWindow.open();
_crfPopupWindow.focus();
}
}
function crfPopupWindow(countermeasureID, recordType) {
var crfPopup = new WindowDef();
crfPopup.target = "CRF_Popup.aspx?countermeasureID=" + countermeasureID + "&" + "recordType=" + recordType;
crfPopup.windowName = "CRFPopup";
crfPopup.toolBar = "no";
crfPopup.resizable = "yes";
crfPopup.scrollbars = "yes";
crfPopup.location = "yes";
crfPopup.width = 350;
crfPopup.height = 400;
return crfPopup;
}
EDIT: Solution
<script type="text/javascript" language="javascript">
function init() {
window.focus();
}
</script>
Have you checked that the 2nd popup has higher z-index CSS property?
First popup can have z-index of, say, 1000, but the second should have then 1001.
window.focus on page load This works

Javascript game with css position

I am trying to make a very simple helicopter game in javascript and I'm currently using css positions to move the objects. but I wanted to know if there was a better/other method for moving objects (divs) when a user is pressing a button
here's a code i've got so far..
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Game 2 helicopter</title>
<script type="text/javascript">
function num(x){
return parseInt(x.replace(/([^0-9]+)/g,''));
}
function getPos(x, y){
var inum=Math.floor(Math.random()*(y+1-x)) + x;
inum=inum;
return inum;
}
function setTop(x,y){ x.style.top = y+'px'; }
function setBot(x,y){ x.style.bottom = y+'px'; }
function setLeft(x,y){ x.style.left = y+'px'; }
function setRight(x,y){ x.style.right = y+'px'; }
function getTop(x){ return num(x.style.top); }
function getBot(x){ return num(x.style.bottom); }
function getLeft(x){ return num(x.style.left); }
function getRight(x){ return num(x.style.right); }
function moveLeft(x,y){
var heli = document.getElementById('heli');
var obj = document.getElementById('obj');
var poss = [20,120,350,400];
var r_pos = getPos(1,4);
var rand_pos = poss[r_pos];
xleft = getLeft(x)-y;
if(xleft>0){
xleft=xleft;
}
else{
xleft=800;
setTop(x,rand_pos);
}
setLeft(x,xleft);
setTimeout(function(){moveLeft(x,y)},10);
checkGame(heli,obj);
}
var heli;
var obj;
function checkGame(x,y){
var obj_right = getLeft(x) + 100;
var yt = getTop(y);
var yb = (getTop(y)+100);
if(getTop(x) >= yt && getTop(x) <= yb && obj_right==getLeft(y)){
endGame();
}
}
function func(){
var x = document.getElementById('heli');
var y = document.getElementById('obj');
alert(getTop(x)+' '+getTop(y)+' '+(getTop(y)+200));
}
function startGame(e){
document.getElementById('park').style.display='block';
document.getElementById('newgame').style.display='none';
heli = document.getElementById('heli');
obj = document.getElementById('obj');
hp = heli.style.top;
op = obj.style.top;
setTop(heli,20);
setLeft(heli,20);
setLeft(obj,800);
setTop(obj,20);
moveLeft(obj,5);
}
function newGameLoad(){
document.getElementById('park').style.display='none';
document.getElementById('newgame').style.display='block';
}
function gamePos(e){
heli = document.getElementById('heli');
obj = document.getElementById('obj');
var keynum;
var keychar;
var numcheck;
if(window.event){ // IE
keynum = e.keyCode;
}
else if(e.which){ // Netscape/Firefox/Opera
keynum = e.which;
}
keychar = String.fromCharCode(keynum); // up=38 down=40 left=37 right=39
/*if(keynum==37){ //left
tl=tl-20;
db.style.left = tl + 'px';
}
if(keynum==39){ //right
//stopPos();
tl=tl+20;
db.style.left = tl + 'px';
}*/
curb = getTop(heli);
if(keynum==38){ //top
setTop(heli,curb-10);
//alert(curb+10);
}
if(keynum==40){ //bottom
setTop(heli,curb+10);
//alert(curb-10);
}
}
function endGame(){
clearTimeout();
newGameLoad();
}
</script>
<style type="text/css">
.play{position:absolute;color:#fff;} #heli{background:url(http://classroomclipart.com/images/gallery/Clipart/Transportation/Helicopter/TN_00-helicopter2.jpg);width:150px;height:59px;}
#obj{background:red;width:20px;height:200px;}
.park{height:550px;border:5px solid brown;border-left:none;border-right:none;}
#newgame{display:none;}
</style>
</head>
<body onload="startGame();" onkeydown="gamePos(event);">
<div class="park" id="park">
<div id="heli" class="play"></div>
<div id="obj" class="play"></div>
</div>
<input type="button" id="newgame" style="position:absolute;top:25%;left:25%;" onclick="startGame();" value="New Game" />
</body>
</html>
Some general comments:
parseInt() already ignores trailing non-numerics, so there's no need for your num() function. If there were, you could write that regex more simply as /\D+/g.
If speed is critical, a marginally faster way to floor a number is x<<0.
All of getPos should just be: return Math.floor(...)+x;. I have no idea why you declare and set a variable, set it to itself, and then return it.
Instead of re-getting the heli and obj items each call to moveLeft(), you should set them once (after the document as loaded) and let moveLeft() be a closure that references them. Same with poss.
You forgot to var your xleft variable, which makes it a global.
You have if (xleft>0){ xleft=xleft; }. This doesn't do anything.
You can declare multiple variables on the same line, e.g. var heli, obj;
Instead of using alert for debugging, use console.log (or better yet, actual breakpoints and stepping through your code). You will find your life far, far easier. Look up Developer Tools for Safari/Chrome or Firebug for Firefox.
There are more global variables such as hp and op.
You should look into a library like jQuery which will make your code easier to develop. For example, you don't have to do the browser-specific tests for events, as it normalizes them.
Use a switch() statement to process your keycodes instead of multiple if statements.
Remove the onload and onkeydown handlers from your body, and instead register them programmatically from your script.
Remove the style attribute from your HTML, and put it in your stylesheet.
Yes do not use a Timer to poll if a event has happened. Use javascript's addEventListener or jQuery's event functions.I would use recommend jQuery as it would probably make writing other parts of your code faster as well.

Categories