einstein
einstein

Reputation: 13850

set cursor on a div element?

How do I set the cursor on a div-element in javascript?

I have a form(div-element not input) with a textstring attached on it. I want the textstring removed and the cursor set at the beginning of the element onclick.

I have removed the content in the div-element with onclick event with: divElement.innerHTML = '';

Now I want the cursor to be set?

Upvotes: 0

Views: 6588

Answers (3)

Spudley
Spudley

Reputation: 168715

If by 'cursor', you mean the text cursor (aka the caret), I presume what you're really asking is how to make a div into an editable content box.

What you need is to set the contentEditable attribute on your div.

If you want it editable from the start, just include it in your HTML code:

<div contentEditable="true">....</div>

If you want to switch it on/off, you can set it in javascript:

mydiv.contentEditable="true"

However, the only time I can think of when it's better to use contentEditable rather than a textarea is if you're writing a WYSIWYG HTML editor.

Most of the rest of the time I would say it's probably preferable to use a <textarea>. You can style it to look like the rest of your page, and you can make it readonly or disabled when you don't want it changed. But it is much easier to work with in a form and in Javascript. The problem with using a div is that it can contain other html tags, which may affect how it works, and will likely open you up to security problems if you make it directly editable.

Upvotes: 1

Matt
Matt

Reputation: 75317

divElement.style.cursor = 'whatever';

If you want to move the cursor to be over the divElement, then you can't.

Upvotes: 0

Spudley
Spudley

Reputation: 168715

If you mean the mouse pointer, use the CSS cursor style like this:

#mydiv {
    cursor: help;
}

There are a whole load of standard options you can use. You can also define a graphic to use as the pointer (though this has cross-browser compatibility issues).

See this page on Quirksmode for more info.

Similarly, if you want to do it dynamically in Javascript, then just set the object's style:

document.getElementById('mydiv').style.cursor = 'help';

Upvotes: 2

Related Questions