2

I have a div:

<div id="test" style="width:auto; height:auto;">
</div>

And a function:

 $(function() {
            $("#test").attr("contentEditable", "true");
            $("#test")
            .attr("tabindex", "0")
            .keydown(function(){ alert(1); return false; })
            .mousemove(function(){ alert(2); return false; });
    });

How can I implement this code in JavaScript without including the JQuery library?

3
  • What browsers are you targeting? Commented Apr 26, 2012 at 5:02
  • 1
    Which versions of ie? Event handling on older versions of IE will require additional code. Commented Apr 26, 2012 at 5:09
  • after handling all the browser compatibility issues, you would also need to handle the document ready state. is there a reason you prefer not to use jquery? with cdn's, there are very little reasons not to. Commented Apr 26, 2012 at 5:56

3 Answers 3

2

You can do it like this in javascript without using jquery, Demo available here JsFiddle You can put it in onload method of body then it will call onload of body or just put it in script section below all controls without putting it in function then it will call when document is ready like jquery method $().ready();

var test = document.getElementById('test');
test.setAttribute("contentEditable", "true");
test.setAttribute("tabindex", "0");
test.onkeydown = function(event) { alert("KeyDown");}    
test.onmousemove = function(event) { alert("MouseMove");}
Sign up to request clarification or add additional context in comments.

1 Comment

You can find the element and save it in a variable to avoid repeated calls to .getElementById(), unless you really like typing.
1
function runme() {
  var elm = document.getElementById("test");
  elm.contentEditable = "true";
  elm.tabIndex = 0;
  elm.onkeydown = function() { alert(1); return false; };
  elm.onmousemove = function() { alert(2); return false; };
}

if(window.addEventListener)
  window.addEventListener("load", runme, false);
else
  window.attachEvent("onload", runme);

Comments

1

Adil has the right idea, but to improve upon it a bit, you could store the element in a variable so you do not have to make a call to get the element every time. So I would change it to look something like this:

var t = document.getElementById('test');

t.setAttribute("contentEditable", "true");
t.setAttribute("tabindex", "0");
t.onkeydown = function(event) { alert("KeyDown");}    
t.onmousemove = function(event) { alert("MouseMove");}

Upvoted Adil for beating me to it and for providing the jsfiddle link :)

updated: nevermind, since you just updated your post

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.