set cursor on a div element? - javascript

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?

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';

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.

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

Related

Can an element with no tag have an onClick function? (Reactjs)

I have a header element:
<h2>☶ Today's Bills</h2>
I want the ☶ (&#9782) icon to have an onClick function, but without giving it a tag so it stays as on <h2> tag.
My approach was this
<h2> <onClick={somfunc}> ☶ </> Today's Bills</h2> // doesn't work
So is there a way to do so? And if not, is there a way to give this part of the <h2> tag the onClick?
I don't want to make it 2 tag-elements and write css to have them aligned as this will probably break something else. I'm relatively new so not having to do so would be better.
that won't work, use a element (like span)
Edit: this JSX need to convert into HTML and need to bind the event to actual element.
This can be done by CSS without inserting another element.
If you absolutely don't want to insert an extra element into the HTML then you can use a pseudo before element.
This can hold the special character and have pointer-events set to auto while the actual h element has pointer-events none set.
h2 {
pointer-events: none;
}
h2::before {
content: "\2636";
pointer-events: auto;
}
<h2 onclick="alert('I have seen a click');">Today's Bills</h2>
[Tested only on Edge/Chrome so far]
However, there may be accessibility issues in that I'm not certain that every screen reader will announce that special character so the possibility of clicking it may be missed by someone using special software.

How refresh the style of an HTML element after changing it using Javascript?

I have an HTML page containing XML. Using Javascript, the XML attributes can be changed when the user clicks a button. (So far, everything works)
However, the attribute that is changed is used in the linked CSS to determine the background color of the element. When the attribute value is changed, the style is not refreshed, so the color doesn't change.
I can alter the javascript to also change the color, but that would involve hardcoding the color, and partially defeat the point of using CSS.
So, it seems to me, I need to do one of two things, and I can't figure out how to do either:
read the color from the CSS, and then assign it using javascript
somehow use javascript to have the CSS re-applied to the document.
Which approach is better? I assume the 2nd is easier, unless there is a side-effect I haven't thought of. And, whichever approach is better, HOW TO DO IT?
My CSS contains:
*[cleared=true] {
background:lightgrey;
}
My XML looks like this:
<Transfer ID="31266" Date="2015-04-14" Cleared="false">
<AccountCharge Account="Unplus">-826.20</AccountCharge>
<AccountCharge Account="Amex">826.20</AccountCharge>
<TransactionID>1504140662984782</TransactionID>
</Transfer>
My Javascript is:
function Reconcile(Element_ID){
try {
var c=document.getElementById(Element_ID);
c.setAttribute('Cleared','True');
}
catch(e) {
alert(e.description);
}
}
I have tried changing the script from modifying 'Cleared' to 'Date', and I can see the date change. The 'Cleared' attribute is not displayed directly by the CSS, but is used to set the formatting of other elements and/or attributes.
Changing the value of 'Cleared' before the page is loaded has the effect I expect - the CSS causes the formatting I expect. However, after the page is loaded, when the javascript changes the value of 'Cleared', no visible change in formatting takes place.
Did you try to assign classes?
Either with pure Javascript:
document.getElementById('selector').className = 'active';
or with jQuery:
jQuery('#selector').addClass('active');
This way you can use CSS classes and not hardcode the colour in your Javascript code.
See implementation of addClass and removeClass in Javascript:
http://jaketrent.com/post/addremove-classes-raw-javascript/
There's some info about changing style of HTML element with jQuery: jQuery changing style of HTML element
There's some more if you change your mind: How to modify STYLE attribute of element with known ID using JQuery
You can either add some extra styles or just switch the target class/id.

Drag-n-Drop on contentEditable elements

There are numerous WYSIWYG editors available on the internet, but I'm yet to find one that implements some form of drag-n-drop implementation.
It is easy to create one's own editor, but I want to the user to be able to drag elements (ie. tokens) from outside the editable area and have them drop it at a location of their choice inside the editable area.
It is easy to inject html at a specific location of an editable element, but how do one determine where the caret should be when the user is dragging a DIV over some element in the editable area. To better illustrate what I'm trying to explain, see the following scenario.
The editable area (either an IFRAME in edit mode or a DIV with its contentEditable attribute set to true) already contains the following text:
"Dear , please take note of ...."
The user now drags an element representing some token from a list of elements, over the editable area, moving the cursor over the text until the caret appear just before the comma (,) in the text as shown above. When the user releases the mouse button at that location, HTML will be injected which could result in something like this:
"Dear {UserFirstName}, please take note of ...".
I do not know if anyone has ever done anything similar to this, or at least know of how one would go about doing this using JavaScript.
Any help will be greatly appreciated.
Here is my approach to solving the issue of custom drag elements on editable elements. The big issue is that one cannot determine the text offset of the mouse cursor when hovering over the editable element. I have tried faking a mouse click to set the caret at the desired position but that did not work. Even if it did, one would not visually see the placement of the caret while dragging, but only the resulting drop.
Since one can bind mouse-over events to elements and not text-nodes, one can set the editable element to be temporarily un-editable. Find all elements and wrap each text-node in a span as to not breaking the flow of the text. Each span should be given a classname so we can find them again.
After the wrapping, one should again find all the wrapped text-nodes and wrap each character with another span with a classname that one can find them again.
Using event delegation one can add an event to the main editable element that will apply a style to each character span that will display the caret, a blinking GIF image as a background.
Again, using event delegation, one should add an event for the mouse-up event (drop event) on each character. One can now determine the offset using the character span's position (offset) within its parent (wrapped text-node). One can now undo all the wrapping, keeping a reference to the calculated offset and while undoing the wrapping keeping a reference to the applicable text-node.
Using the range & selection objects of the browser, one can now set the selection using the calculated offset to the applicable text-node and inject the required HTML at the newly set selection (caret position), et viola!
Here follows a snippet using jQuery that will find textnodes, wrap them:
editElement.find("*:not(.text-node)").contents().filter(function(){
return this.nodeType != 1;
}).wrap("<span class=\"text-node\"/>");
To find each text-node and wrap each character, use:
editElement.find(".text-node").each(function()
{
var textnode = $(this), text = textnode.text(), result = [];
for (var i = 0; i < text.length; i++) result.push(text.substr(i, 1));
textnode.html("<span class=\"char\">"
+ result.join("</span><span class=\"char\">") + "</span>");
});
To undo the wrapping:
editElement.find(".text-node").each(function()
{
this.parentNode.replaceChild(document.createTextNode($(this).text()), this);
});
Hope this approach helps those having similar challenges
If I understand what you're saying, then this is just basic drag and drop. The solution below should be close to the best answer for FIREFOX. I'm sure there are different functions for IE. Go to http://www.html5rocks.com/en/tutorials/dnd/basics/ for more help.
Set the "draggable" attribute of the object you want to drag, and set the object's "ondragstart" method to "dragStartHandler" or whatever your function is called.
// You can set this to 'text/plain' if you don't want to insert HTML content
var internalDNDType = 'text/html';
function dragStartHandler(event) {
// This is whatever html data you want to insert.
var textContent = "<b>"+userFirstName+"</b>";
event.dataTransfer.setData(internalDNDType, textContent);
event.dataTransfer.effectAllowed = 'copy';
}
function dragEnterHandler(event)
{
event.preventDefault();
return false;
}
function dragOverHandler(event)
{
event.preventDefault();
return false;
}
function dropHandler(event) {
event.preventDefault();
event.stopPropogation();
return false;
}
Currently an HTML5 API is being developed to do this, but unfortunately IE doesn't support it. Edit: Apparently IE actually does support drag and drop, but I'm not very familiar with how it works. Try Googling "IE drag and drop".
Try looking at these sites:
https://developer.mozilla.org/en/DragDrop/Drag_and_Drop
http://html5doctor.com/native-drag-and-drop/
http://www.thebuzzmedia.com/html5-drag-and-drop-and-file-api-tutorial/
http://www.webreference.com/programming/javascript/dragdropie/ (Drag and Drop in IE)

Transforming highlighted text inside an element using javascript

My goal is to be able to get the highlighted text within a document, but only if that text is within a given section, and then apply a certain style to that selected text after clicking a div tag. I'll explain what I mean:
So, having looked at window.getSelection() and document.selection.createRange().text, I attempted to use elmnt.getSelection() or elmnt.selection.createRange().text for some HTML element, elmnt. However, it doesn't seem to work, so that idea seems pretty null. This means I can't use this idea to determine the text that is highlighted within a given location. In case this doesn't make sense, essentially, I want html code that looks like this:
<body>
<div id="content">Stuff here will not be effected</div>
<div id="highlightable">Stuff here can be effected when highlighted</div>
<div id="morecontent">Stuff here will also not be effected</div>
</body>
So that whenever I've highlighted text, clicking on a specified div will apply the proper CSS.
Now, on to the div tags. Basically, here's what I've got on that:
$('.colorpicker').click( function(e)
{
console.log(getSelectedText());
}
Eventually, all I want this to highlight the selected text and have the div tag change the color of the selected text to that of the respective div tag that I've selected. Neither of these seems to be working right now, and my only guess for the reason of the div tag is that it unhighlights whatever I've got selected whenever I click on the div tag.
Fallbacks:
If there is more than one time that 'abc' is found on the page and I highlight to color 'abc', I would like that only that copy of 'abc' be highlighted.
I know this is a lot in one question, but even if I could get a little head start on this idea, my next personal project would be going a lot more smoothly. Thanks. :)
The key in the solution to this will be working with the objects that represent text ranges in browsers, not the selected text itself. Look into methods available to you in both the FireFox Range and IE TextRange objects. Both of these contain means of replacing the selected text with your own markup (e.g. a span wrapping your selected text.)
For FF look into Range.getRangeAt(0).surroundContents(element)
For IE look into TextRange.pasteHTML()
I must warn you though... You'll probably end up down a scary path of browser quirks if you go through with this. Already from the get-go you're supporting two different objects for two of the major browsers.

How to make a div with a blinking cursor and editable text without using <input>?

I need to make a div layer so that when you click on it you will have your cursor there blinking and you can insert/delete text just like <input type="text"> does, except that I do not want to use it as it is slightly too limited to my case.
I can definitely use JavaScript.
DIV element has (other elements as well) contentEditable property that you can set in Javascript to true.
getElementById('YourDiv').contentEditable = true;
You can make the div editable by setting its contentEditable attribute / property to true. However, for anything that is slightly more powerful or flexible then very basic editing, you might want to look at existing solutions such as:
TinyMCE
Kevin Roth's RTE
The YUI editor
Jquery can be used like this:
$.('#yourDiv').click(function() {
$(this).attr('contenteditable', 'true');
});
I suggest you to use a textarea, and if that's not enough, use a WYSIWYG editor like tinyMCE or FCKeditor.
as I understand your problem, you can resove it by adding textarea into your div. It is very simply to make this textarea autosize to occupy whole div area and looks like this div.
As for contentEditable, I have seen some browsers, supported this feature for div-element and does not. Anyway, you can use iframe in your div. It's document-element can have contentEditable.
contenteditable attribute could be used for this purpose. Following code line has been tested in IE7 and Firefox 3.0.10. One part, I have noticed that this attribute should be used in lower case only; else it wont work in Firefox.
<div id="Div_ID" contenteditable="true" tabindex="0">
Enter text here
</div>

Categories

Resources