Colour change on dragenter and dragleave not working jquery - javascript

When dragging and entering the <div class="upload-cont"> the color changes perfectly from gray to black of border and text and when it comes to the <span class="add-text"> it changes back to gray.
CSS:
.upload-cont{
cursor:pointer;
margin-left:130px;
display:inline-block;
border:2px dashed #a8a8a8;
max-width:220px;
max-height:180px;
min-width:220px;
min-height:180px;
position:relative;
border-radius:3px;
}
.add-text{
display:block;
font-size:10px;
font-weight:bold;
color:#999;
word-wrap:break-word;
text-align:center;
width:100px;
top:37%;
left:25%;
position:absolute;
}
.add-text:hover{ color:black; }
HTML:
<div class="upload-cont">
<span class="add-text">
Click to add or<br/>
Drag and drop image here
</span>
</div>
Jquery:
$(document).ready(function () {
$(".upload-cont,.add-text").on('dragenter', function (e) {
$(".upload-cont").css({
"border": "2px dashed black"
});
$(".add-text").css({
"color": "black"
});
});
$(".upload-cont").on('dragleave', function (e) {
$(".upload-cont").css("border", "2px dashed #a8a8a8");
$(".add-text").css({
"color": "#a8a8a8"
});
});
});
What can i do to remain the black color for the border and text when entering <span class="add-text">
Check this jsfiddle: http://jsfiddle.net/rpABs/
Thanks in advance

Use dragover instead of dragenter since dragleave fires when you enter child elements
$(".upload-cont,.add-text").on('dragover', function (e) {
$(".upload-cont").css({
"border": "2px dashed black"
});
$(".add-text").css({
"color": "black"
});
});
$(".upload-cont").on('dragleave', function (e) {
$(".upload-cont").css("border", "2px dashed #a8a8a8");
$(".add-text").css({
"color": "#a8a8a8"
});
});
DEMO

Apparently this problem is more recurrent than I thought since I found at least 5 questions associated with the same topic (and I will answer all related with this issue).
Unlike "mouseover", the events "dragover" and "dragleave" do not consider the child elements as a whole, so each time the mouse passes over any of the children, "dragleave" will be triggered.
Thinking about the upload of files, I created a widget that allows:
Drag and drop desktop files using $ _FILES
Drag and drop to browser images/elements or url using $ _POST and cURL
Attach a device file using button using $ _FILES
Use input to write/paste url images/elements using $ _POST and cURL
The problem: As everything, both form inputs and images, are within DIVs children, "dragleave" was triggered even if it did not leave the dashed line. Using the attribute "pointer-events: none" is not an alternative since methods 3 and 4 need to trigger "onchange" events.
The solution? An overlapping DIV that covers all the drop-container when the mouse enters, and the only one with child elements with "pointer-events: none".
The structure:
div #drop-container: main div, keep all togheter
div #drop-area: "dragenter" listener and inmediate trigger #drop-pupup
div #drop-pupup: at same leval as #drop-area, "dragenter", "dragleave" and "drop" listener
Then, when the mouse enters by dragging an element to #drop-area, inmediatly shows #drop-pupup ahead and successively the events are on this div and not the initial receiver.
Here is the JS/jQuery code. I took the liberty to leave the PoC so do not lose all the time I lost.
jQuery(document).on('dragover', '#drop-area', function(event) {
event.preventDefault();
event.stopPropagation();
jQuery('#drop-popup').css('display','block');
});
jQuery(document).on('dragover dragleave drop', '#drop-popup', function(event) {
event.preventDefault();
event.stopPropagation();
console.log(event.type);
// layout and drop events
if ( event.type == 'dragover') {
jQuery('#drop-popup').css('display','block');
}
else {
jQuery('#drop-popup').css('display','none');
if ( event.type == 'drop' ) {
// do what you want to do
// for files: use event.originalEvent.dataTransfer.files
// for web dragged elements: use event.originalEvent.dataTransfer.getData('Text') and CURL to capture
}
}
});
body {
background: #ffffff;
margin: 0px;
font-family: sans-serif;
}
#drop-container {
margin: 100px 10%; /* for online testing purposes only */
width: 80%; /* for jsfiddle purposes only */
display: block;
float: left;
overflow: hidden;
box-sizing: content-box;
position: relative; /* needed to use absolute on #drop-popup */
border-radius: 5px;
text-align: center;
cursor: default;
border: 2px dashed #000000;
}
#drop-area {
display: block;
float: left;
padding: 10px;
width: 100%;
}
#drop-popup {
display: none;
box-sizing: content-box;
position: absolute;
width: 100%;
top: 0;
left: 0;
background: linear-gradient(to BOTTOM, rgba(245, 245, 245, 1) , rgba(245, 245, 245, 0));
height: 512px;
padding: 20px;
z-index: 20;
}
#drop-popup > p {
pointer-events: none;
}
<html>
<head>
<title>Drag and Drop</title>
</head>
<body>
<div id="drop-container">
<div id="drop-area">
<p>Child paragraph content inside drop area saying "drop a file or an image in the dashed area"</p>
<div>This is a child div No. 1</div>
<div>This is a child div No. 2</div>
</div>
<div id="drop-popup">
<p>This DIV will cover all childs on main DIV dropover event and current P tag is the only one with CSS "pointer-events: none;"</p>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.4.1.min.js" type="text/javascript"></script>
</body>
<html>
About jQuery "on", use it with the div id inside on, so you can start event triggers starting "uploading box" hidden.
Finally, I preferred to use "dragover" over "dragenter" because it has a small delay (milliseconds) that favors performance
(https://developer.mozilla.org/en-US/docs/Web/API/Document/dragover_event).

The dragover event fires constantly as you're dragging, so I'm not a fan of that solution. I've written a little library called Dragster that gives me better enter & leave events.

Related

Javascript Make Div appear for 2 seconds after mouse press

I've been having problems with creating a colored block which is hidden, and then appears after a mouse press (no where specific, anywhere on the page), then stays there for 2 seconds and then disappears again... until another mouse press happens, and the whole thing happens again. Have been experimenting with '.click(function' and other things but haven't been able to make it work.
At the moment I have a DIV layer like this...
HTML:
<div class="overlay"></div>
CSS:
.overlay {
position: absolute;
z-index: 1000;
right: 240px;
top: 500px;
width: 1000px;
height: 100px;
background: rgba(255, 255, 200, 100);
}
I'm quite new to javascript so any advice will be very helpful.
You can do it using setTimeout in jQuery
$( "#target" ).on( "click", function() {
$("#messageBox").hide().slideDown();
setTimeout(function(){
$("#messageBox").hide();
}, 2000);
});
#messageBox {
display:inline-block;
float:right;
border:1px solid #060;
background:#FFC;
padding:10px 20px;
box-shadow:2px 2px 4px #666;
color:#060;
font-weight:bold;
display:none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="messageBox">
Hi there.
</div>
<input type="button" id ="target" value="click"/>
The jQuery(document) does the trick as it will consider click for the whole document and not to a specific place on page.
jQuery(document).click(function(event) {
var $div = $(".overlay");
if ($div.is(":visible")) { return; }
$div.show();
setTimeout(function() {
$div.hide();
}, 2000);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Doing this you do need a target div or element to fire an event on click. This will allow you to fire the event on the whole document.

How to remove Jquery event if another element has certain class?

I am trying to build a simple dropdown plugin for small project of mine. I do not want to use ready plugins, I want to learn by making one on my own.
html:
<div>
<span class="dropdown_triger">press</span>
<div class="content dropdown-closed">
</div>
</div>
css:
span{
display:inline-block;
background: green;
padding: 5px;
}
.content{
position: absolute;
top: 40px;
border: solid 1px black;
width: 200px;
height: 100px;
}
.dropdown-closed { display: none; }
.dropdown-open { display: block; }
and JS:
$(document).ready(function(){
$('body').on('click', '.dropdown_triger', function(e){
var $wrapper = $(this).parent();
var $content = $(this).next();
var $triger = $(this);
if($triger.hasClass('selected')){
$(document).off('mouseup.dropdownDocClick');
console.log('hasClass');
}
$triger.toggleClass('selected');
$content.toggleClass('dropdown-closed dropdown-open');
$(document).on('mouseup.dropdownDocClick',function (e){
console.log('fire');
if (!$wrapper.is(e.target) && $wrapper.has(e.target).length === 0){
if($content.hasClass('dropdown-open')){
$content.toggleClass('dropdown-closed dropdown-open');
$(document).off('mouseup.dropdownDocClick');
}
}
});
});
});
Everything works except for this place:
if($triger.hasClass('selected')){
$(document).off('mouseup.dropdownDocClick');
console.log('hasClass');
}
I expect that mouseup event would not fire anymore but it does. Here is a fiddle, just try it. If I open dropdown, mouseup event is attached to document and keeps firing until I have clicked outside container thus closed dropdown.
But if I close dropdown by clicking again on triger button(span in my example) event is not removed and I can not understand why?

Onmouseover/out deactivate and reactivate in jQuery

I have a search function that does 3 things:
1) first, when a user hover over the icon, it should change the icon, and the color of border around it as well:
HTML:
<div class="searchbox">
<img id="search" src="Icons/magnifier2.png"
onmouseover="this.src='Icons/magnifier.png'"
onmouseout="this.src='Icons/magnifier2.png'"/>
</div>
CSS:
.searchbox #search {
display: inline;
border: 2px solid #c8c8c8;
position: relative;
height: 20px;
width: 20px;
float: right;
padding: 4px;
border-radius: 5px;
transition: all 500ms;
}
.searchbox #search:hover {
display: inline;
border: 2px solid #808080;
position: relative;
float: right;
padding: 4px;
border-radius: 5px;
transition: all 500ms;
}
So far so good. In this bit, im unsure why the image isnt applied any transition at all when hovered... Is there a way in which you can change color on a single .png icon, instead of juggling between two .pngs?
2) The user is supposed to click on this icon, whereafter it expands with a new icon and a changed border width (padding-left: 130px;). Here goes the following jQuery code:
$(function () {
var search = $("#search");
search.click(function () {
search.attr("src", "Icons/magnifier.png").css({
"border": "2px",
"border-style": "solid",
"border-color": "#808080",
"padding-left": "130px",
"transition": "all 500ms" });
});
});
3) When the user clicks on the HTML body, the border should slide back to normal position and apply the original CSS:
$('html').click(function (e) {
if (e.target.id != 'search') {
$("#search").attr("src", "Icons/magnifier2.png");
$("#search").removeAttr('style');;
}
});
My issue is, the HTML onmouseover/out shown in the top of my post, is still active when the function is fired upon clicking the icon.(if i place my mouse inside and outside the expanded border, it still changes the icon.)
My idea of an easy fix:
It would be a lot easier if the :hover parameter in the CSS could change both the color of the .png and the border, however i've been searching alot for this specific solution, and it doesnt seem to be available!
The second solution would be to add some kind of code in the jQuery, search.click(function() that deactivates the onmouseover/out and reactivates it in the 2'nd .click(function().
I hope im clear enough with my question.
How do i overcome this onmouseover/out issue?
I've added a jsfiddle just for you to see my example:
https://jsfiddle.net/bfytnbs3/
It would be a lot easier if the :hover parameter in the CSS could
change both the color of the .png and the border, however i've been
searching alot for this specific solution, and it doesnt seem to be
available!
You can accomplish that using a CSS sprite. More reading is here: http://www.w3schools.com/css/css_image_sprites.asp
Basically, you'd have one magnifier.png image that would have both states for the icon. Then you'd use some CSS to switch between them.
.searchbox {
background: url('magnifier.png') 0px 0px;
}
.searchbox:hover {
background: url('magnifier.png') 0px -25px;
}
In this example, you'd have a sprite image that was 25px by 50px, with each state of the image being 25px by 25px.
Hope that helps!
Edit to add: Here is a JS Fiddle Example so you can see how it works:
https://jsfiddle.net/s51zjre4/1/

Change background color of div using conditional statement

I have 2 divs side by side and by default one is hidden and one is visible.
I have a jQuery function which, when mouseenter the visible div, the hidden one shows. And when mouseenter again, it becomes hidden again. (This is for a login box)
However - I want the always visible div (the mouseenter target) to change color depending on what state the toggled div is in. So far, I can get it to change color upon first mouseenter but it won't change again after that.
Here is the code I have so far:
<script>
$(document).ready(function () {
$("#loginBox").hide();
$("#sideBar").show();
$('#sideBar').mouseenter(function () {
$("#loginBox").toggle("slide");
if ($('#loginBox').is(":visible")) {
$("#sideBar").css("background-color","blue");
} else if ($('#loginBox').is(":hidden")) {
$("#sideBar").css("background-color","yellow");
}
});
});
</script>
So it starts off in its default color (grey by the style sheet) and when mouseenters it loginBox becomes visible and the sideBar turns blue. But when mouseenters again, even though loginBox becomes hidden, the sideBar remains blue.
JSFiddle
You can put the check in the complete function of toggle
$(document).ready(function() {
$("#aside").hide();
$("#asidebar").show();
$('#asidebar').mouseenter(function() {
$("#aside").toggle("slide", function() {
var onOrOff = $('#asidebar').css("background-color");
if ($('#aside').is(":visible")) {
$("#asidebar").css("background-color", "blue");
} else if ($('#aside').is(":hidden")) {
$("#asidebar").css("background-color", "yellow");
}
});
});
});
#asidebar {
float: right;
/* top: -205px; */
position: relative;
/*
Editing purposes */
background-color: rgba(120, 120, 120, 0.5);
width: 25px;
/*min height of container */
height: 400px;
margin: 5px;
padding: 1px;
font-family: helvetica;
}
#aside {
float: right;
/* top: -205px; */
position: relative;
/*
Editing purposes
background-color: blue; */
width: 250px;
border-left-style: dashed;
border-color: rgba(120, 120, 120, 0.5);
/*min height of container */
margin: 5px;
padding: 0;
font-family: helvetica;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="asidebar">Mouse Over</div>
<div id='aside'>Slide box</div>
You are better off putting the styles on a class and toggling that instead. Something like
...
$('#sideBar').mouseenter(function () {
$("#loginBox").toggle("slide");
$("#sideBar").addClass("semanticallyNamedClassForBlue");
$("#sideBar").toggleClass("semanticallyNamedClassForYellow");
});
...
CSS:
#sideBar.semanticallyNamedClassForBlue {background: blue}
#sideBar.semanticallyNamedClassForYellow {background: yellow}
as per this jsfiddle adapted from user3787555's http://jsfiddle.net/3rQNb/3/
Explanation:
On load the sidebar is grey.
on first hover both the yellow and blue classes are added to the element, but as the yellow class is last in the css source, it wins the cascade.
on next hover, the yellow class is removed, so the blue now wins.
I added the id to the css rule to get the specificity up enough - as you know a #id beats a .class in the cascade
If you want to learn more, A List Apart's CSS articles and Remy Sharp's JQuery for designers may give you some joy. If you want to learn more on specificity look at star wars specificity super awesome

contenteditable single-line input

For an application we're developing at the company where I work, we need an input that supports inserting emoticons inside our JS-based web app. We're currently using an input with the emoticon shortcodes (ie ':-)') and would like to switch to inserting actual, graphical images.
Our original plan was to use a contenteditable <div>. We're using listeners for the paste event as well as the different key/mouse interactions to ensure no unwanted markup enters the contenteditable (we strip text out of its container tags and leave only image tags that we inserted ourselves).
However, the problem right now is that the div resizes if you put in enough content (ie its height increases). We don't want this to happen, nor is it acceptable for the text to just be hidden (ie plain overflow: hidden). So:
Is there a way to make the contenteditable div behave like a single-line input?
I'd like it best if there is a relatively simple attribute/css property that I've missed that will do what I want, but if necessary CSS+JS suggestions will also be appreciated.
[contenteditable="true"].single-line {
white-space: nowrap;
width:200px;
overflow: hidden;
}
[contenteditable="true"].single-line br {
display:none;
}
[contenteditable="true"].single-line * {
display:inline;
white-space:nowrap;
}
<div contenteditable="true" class="single-line">
This should work.
</div>​
Other answers are wrong and contain few mistakes (on 2019-05-07). Other solutions suggest to use "white-space: nowrap" (prevents carrying to another line) + "overflow: hidden" (prevents long text going beyond the field) + hiding <br> and other.
First mistake in that solutions is "overflow: hidden" also prevents scrolling the text. User will not be able to scroll the text by:
Pressing mouse middle button
Selecting the text and moving mouse pointer to the left or right
Using horizontal mouse scroll (when user have such a thing)
The only way he can scroll is using keyboard arrows.
You can solve this problem by using "overflow: hidden" and "overflow: auto" (or "scroll") at the same time. You should create parent div with "overflow: hidden" to hide content user should not see. This element must have input borders and other design. And you should create child div with "overflow-x: auto" and "contenteditable" attribute. This element will have scrollbar so user can scroll it without any limitations and he will not see this scrollbar because of hiding overflow in parent element.
Example of solution:
document.querySelectorAll('.CETextInput').forEach(el => {
//Focusing on child element after clicking parent. We need it because parent element has bigger width than child.
el.parentNode.addEventListener('mousedown', function(e) {
if (e.target === this) {
setTimeout(() => this.children[0].focus(), 0);
}
});
//Prevent Enter. See purpose in "Step 2" in answer.
el.parentNode.addEventListener('keydown', function(e) {
if (e.keyCode === 13)
e.preventDefault();
});
});
.CETextInputBorder { /*This element is needed to prevent cursor: text on border*/
display: inline-block;
border: 1px solid #aaa;
}
.CETextInputCont {
overflow: hidden;
cursor: text; /*You must set it because parent elements is bigger then child contenteditable element. Also you must add javascript to focus child element on click parent*/
/*Style:*/
width: 10em;
height: 1em;
line-height: 1em;
padding: 5px;
font-size: 20px;
font-family: sans-serif;
}
.CETextInput {
white-space: pre; /*"pre" is like "nowrap" but displays all spaces correctly (with "nowrap" last space is not displayed in Firefox, tested on Firefox 66, 2019-05-15)*/
overflow-x: auto;
min-height: 100%; /*to prevent zero-height with no text*/
/*We will duplicate vertical padding to let user click contenteditable element on top and bottom. We would do same thing for horizontal padding but it is not working properly (in all browsers when scroll is in middle position and in Firefox when scroll is at the end). You can also replace vertical padding with just bigger line height.*/
padding: 5px 0;
margin-top: -5px;
outline: none; /*Prevent border on focus in some browsers*/
}
<div class="CETextInputBorder">
<div class="CETextInputCont">
<div class="CETextInput" contenteditable></div>
</div>
</div>
Step 2: Solving problem with <br> and other:
Also there is a problem that user or extensions can paste
<br> (can be pasted by user)
<img> (may have big size) (can be pasted by user)
elements with another "white-space" value
<div> and other elements that carry text to another line
elements with unsuitable "display" value
But advise to hide all <br> is wrong too. That is because Mozilla Firefox adds <br> element to empty field (I guess it may be workaround of bug with text cursor disappearing after deleting last character; checked in Firefox 66 released on 2019-03-19). If you hide this element then when user moves focus to field caret will be set in this hidden <br> element and text cursor will be hidden too (always).
You can fix this if you will be <br> when you know field is empty. You need some javascript here (you cannot use :empty selector because field contains <br> elements and not empty). Example of solution:
document.querySelectorAll('.CETextInput').forEach(el => {
//OLD CODE:
//Focusing on child element after clicking parent. We need it because parent element has bigger width than child.
el.parentNode.addEventListener('mousedown', function(e) {
if (e.target === this) {
setTimeout(() => this.children[0].focus(), 0);
}
});
//Prevent Enter to prevent blur on Enter
el.parentNode.addEventListener('keydown', function(e) {
if (e.keyCode === 13)
e.preventDefault();
});
//NEW CODE:
//Update "empty" class on all "CETextInput" elements:
updateEmpty.call(el); //init
el.addEventListener('input', updateEmpty);
function updateEmpty(e) {
const s = this.innerText.replace(/[\r\n]+/g, ''); //You must use this replace, see explanation below in "Step 3"
this.classList.toggle('empty', !s);
}
});
/*OLD CODE:*/
.CETextInputBorder { /*This element is needed to prevent cursor: text on border*/
display: inline-block;
border: 1px solid #aaa;
}
.CETextInputCont {
overflow: hidden;
cursor: text; /*You must set it because parent elements is bigger then child contenteditable element. Also you must add javascript to focus child element on click parent*/
/*Style:*/
width: 10em;
height: 1em;
line-height: 1em;
padding: 5px;
font-size: 20px;
font-family: sans-serif;
}
.CETextInput {
white-space: pre; /*"pre" is like "nowrap" but displays all spaces correctly (with "nowrap" last space is not displayed in Firefox, tested on Firefox 66, 2019-05-15)*/
overflow-x: auto;
min-height: 100%; /*to prevent zero-height with no text*/
/*We will duplicate vertical padding to let user click contenteditable element on top and bottom. We would do same thing for horizontal padding but it is not working properly (in all browsers when scroll is in middle position and in Firefox when scroll is at the end). You can also replace vertical padding with just bigger line height.*/
padding: 5px 0;
margin-top: -5px;
outline: none; /*Prevent border on focus in some browsers*/
}
/*NEW CODE:*/
.CETextInput:not(.empty) br,
.CETextInput img { /*We hide <img> here. If you need images do not hide them but set maximum height. User can paste image by pressing Ctrl+V or Ctrl+Insert.*/
display: none;
}
.CETextInput * {
display: inline;
white-space: pre;
}
<!--OLD CODE:-->
<div class="CETextInputBorder">
<div class="CETextInputCont">
<div class="CETextInput" contenteditable></div>
</div>
</div>
Step 3: Solving problem with getting value:
We hided <br> elements so "innerText" value will not contain them. But:
When "empty" class is set result may contain <br> elements.
Your other styles or extensions may override "display: none" by "!important" mark or by rule with higher priority.
So when you get value you should make replace to avoid accidental getting line breaks:
s = s.replace(/[\r\n]+/g, '');
Do not use javascript for hiding <br>
Also you could solve the problem with <br> by removing them by javascript but this is very bad solution because after every removing user cannot use "undo" action anymore for canceling changes was made before removing.
Also you could use document.execCommand('delete') to delete <br> but it is hard to implement + user can undo your deletion and restore <br> elements.
Adding placeholder
It was not asked in question but I guess many people using single-line contenteditable elements will need it. Here is example how to make placeholder using css and "empty" class we talked above:
//OLD CODE:
document.querySelectorAll('.CETextInput').forEach(el => {
//Focusing on child element after clicking parent. We need it because parent element has bigger width than child.
el.parentNode.addEventListener('mousedown', function(e) {
if (e.target === this) {
setTimeout(() => this.children[0].focus(), 0);
}
});
//Prevent Enter to prevent blur on Enter
el.parentNode.addEventListener('keydown', function(e) {
if (e.keyCode === 13)
e.preventDefault();
});
//Update "empty" class on all "CETextInput" elements:
updateEmpty.call(el); //init
el.addEventListener('input', updateEmpty);
function updateEmpty(e) {
const s = this.innerText.replace(/[\r\n]+/g, ''); //You must use this replace, see explanation below in "Step 3"
this.classList.toggle('empty', !s);
//NEW CODE:
//Make element always have <br>. See description in html. I guess it is not needed because only Firefox has bug with bad cursor position but Firefox always adds this element by itself except on init. But on init we are adding it by ourselves (see html).
if (!s && !Array.prototype.filter.call(this.children, el => el.nodeName === 'BR').length)
this.appendChild(document.createElement('br'));
}
});
/*OLD CODE:*/
.CETextInputBorder { /*This element is needed to prevent cursor: text on border*/
display: inline-block;
border: 1px solid #aaa;
}
.CETextInputCont {
overflow: hidden;
cursor: text; /*You must set it because parent elements is bigger then child contenteditable element. Also you must add javascript to focus child element on click parent*/
/*Style:*/
width: 10em;
height: 1em;
line-height: 1em;
padding: 5px;
font-size: 20px;
font-family: sans-serif;
}
.CETextInput {
white-space: pre; /*"pre" is like "nowrap" but displays all spaces correctly (with "nowrap" last space is not displayed in Firefox, tested on Firefox 66, 2019-05-15)*/
overflow-x: auto;
min-height: 100%; /*to prevent zero-height with no text*/
/*We will duplicate vertical padding to let user click contenteditable element on top and bottom. We would do same thing for horizontal padding but it is not working properly (in all browsers when scroll is in middle position and in Firefox when scroll is at the end). You can also replace vertical padding with just bigger line height.*/
padding: 5px 0;
margin-top: -5px;
outline: none; /*Prevent border on focus in some browsers*/
}
.CETextInput:not(.empty) br,
.CETextInput img { /*We hide <img> here. If you need images do not hide them but set maximum height. User can paste image by pressing Ctrl+V or Ctrl+Insert.*/
display: none;
}
.CETextInput * {
display: inline;
white-space: pre;
}
/*NEW CODE:*/
.CETextInput[placeholder].empty::before { /*Use ::before not ::after or you will have problems width first <br>*/
content: attr(placeholder);
display: inline-block;
width: 0;
white-space: nowrap;
pointer-events: none;
cursor: text;
color: #b7b7b7;
padding-top: 8px;
margin-top: -8px;
}
<!--OLD CODE:-->
<div class="CETextInputBorder">
<div class="CETextInputCont">
<div class="CETextInput" placeholder="Type something here" contenteditable><br></div>
</div>
</div>
<!--We manually added <br> element for Firefox browser because Firefox (tested on 2019-05-11, Firefox 66) has bug with bad text cursor position in empty contenteditable elements that have ::before or ::after pseudo-elements.-->
Solution with only one div and "scrollbar-width"
You can also use only one div by setting "overflow-x: auto", "overflow-y: hidden" and "scrollbar-width: none". But "scrollbar-width" is new property and works only in Firefox 64+ and no other browsers yet.
You can also add:
webkit-prefixed version: "-webkit-scrollbar-width: none"
non-standardized ".CETextInput::-webkit-scrollbar { display: none; }" (for webkit-based browsers)
"-ms-overflow-style: none"
I would not recommend to use this solution, but here is example:
//OLD CODE:
document.querySelectorAll('.CETextInput').forEach(el => {
//Focusing on child is not needed anymore
//Prevent Enter to prevent blur on Enter
el.addEventListener('keydown', function(e) {
if (e.keyCode === 13)
e.preventDefault();
});
//Update "empty" class on all "CETextInput" elements:
updateEmpty.call(el); //init
el.addEventListener('input', updateEmpty);
function updateEmpty(e) {
const s = this.innerText.replace(/[\r\n]+/g, ''); //You must use this replace, see explanation below in "Step 3"
this.classList.toggle('empty', !s);
}
});
/*NEW CODE:*/
.CETextInput {
white-space: pre; /*"pre" is like "nowrap" but displays all spaces correctly (with "nowrap" last space is not displayed in Firefox, tested on Firefox 66, 2019-05-15)*/
overflow-x: auto; /*or "scroll"*/
overflow-y: hidden;
-webkit-scrollbar-width: none; /*Chrome 4+ (probably), webkit based*/
scrollbar-width: none; /*FF 64+, Chrome ??+, webkit based, Edge ??+*/
-ms-overflow-style: none; /*IE ??*/
/*Style:*/
width: 10em;
height: 1em;
line-height: 1em;
padding: 5px;
border: 1px solid #aaa;
font-size: 20px;
font-family: sans-serif;
}
.CETextInput::-webkit-scrollbar {
display: none; /*Chrome ??, webkit based*/
}
/*OLD CODE:*/
.CETextInput:not(.empty) br,
.CETextInput img { /*We hide <img> here. If you need images do not hide them but set maximum height. User can paste image by pressing Ctrl+V or Ctrl+Insert.*/
display: none;
}
.CETextInput * {
display: inline;
white-space: pre;
}
<!--NEW CODE:-->
<div class="CETextInput" contenteditable></div>
This solution has 3 problems with paddings:
In Firefox (tested on 2019-05-11, Firefox 66) there is no right padding when long text is typed. That is because Firefox does not display bottom or right padding when using padding in the same element that have scrollbar and when content is scrolled to the end.
In all browsers there is no padding when scrolling long text in middle position. It looks worse. <input type="text"> does not have this problem.
When user press home or end browsers scroll to place paddings are not visible.
To solve these problems you need use 3 elements like we used before but in this case you don't need use scrollbar-width. Our solution with 3 elements does not have these problems.
Other problems (in every solution):
Blur on pasting text ends with line break. I will think how to fix it.
When using paddings this.children[0].focus() is not enough in webkit-based browsers (cursor position is not where user clicked). I will think how to fix it.
Firefox (tested on 2019-05-11, Firefox 66): When short text is typed user cannot select last word by double clicking on the right of it. I will think about it.
When user starts text selection in the page he can end it in our field. Usual <input type="text"> does not have this behavior. But I don't think it is critical.
I think you are looking for a contenteditable div with only one line of text that scrolls horizontally when it overflows the div. This should do the trick: http://jsfiddle.net/F6C9T/1
div {
font-family: Arial;
font-size: 18px;
min-height: 40px;
width: 300px;
border: 1px solid red;
overflow: hidden;
white-space: nowrap;
}
<div contenteditable>
Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.
</div>
The min-height: 40px incorporates the height for when the horizontal scroll bar appears. A min-height:20px would automatically expand when the horizontal scroll bar appears, but this doesn't work in IE7 (though you could use conditional comments to apply separate styling if you wanted it).
I adapted the #tw16 accepted solution (on 5th Dec 2019) to add in scrolling. The trick was to add scrolling using overflow-x: auto but then hide the scrollbar (https://stackoverflow.com/a/49278385)
/* Existing Solution */
[contenteditable="true"].single-line {
white-space: nowrap;
width: 200px;
overflow: hidden;
}
[contenteditable="true"].single-line br {
display:none;
}
[contenteditable="true"].single-line * {
display:inline;
white-space:nowrap;
}
/* Make Scrollable */
[contenteditable="true"].single-line {
overflow-x: auto;
overflow-y: hidden;
scrollbar-width: none; /* Firefox */
-ms-overflow-style: none; /* Internet Explorer 10+ */
}
[contenteditable="true"].single-line::-webkit-scrollbar { /* WebKit */
width: 0;
height: 0;
}
<div contenteditable="true" class="single-line">
This should scroll when you have really long text!
</div>​
Here's a relatively simple solution that uses the contenteditable's input event to scan the dom and filter out various flavors of new lines (so it should be robust against copy/paste, drag 'n drop, hitting enter on the keyboard, etc). It condenses multiple TextNodes into single TextNodes, strips newlines from TextNodes, kills BRs, and puts a "display: inline" on any other element that it touches. Tested on Chrome, no guarantees anywhere else.
var editable = $('#editable')
editable.on('input', function() {
return filter_newlines(editable);
});
function filter_newlines(div) {
var node, prev, _i, _len, _ref, _results;
prev = null;
_ref = div.contents();
_results = [];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
node = _ref[_i];
if (node.nodeType === 3) {
node.nodeValue = node.nodeValue.replace('\n', '');
if (prev) {
node.nodeValue = prev.nodeValue + node.nodeValue;
$(prev).remove();
}
_results.push(prev = node);
} else if (node.tagName.toLowerCase() === 'br') {
_results.push($(node).remove());
} else {
$(node).css('display', 'inline');
filter_newlines($(node));
_results.push(prev = null);
}
}
return _results;
}
#editable {
width: 200px;
height: 20px;
border: 1px solid black;
}
<div id="editable" contenteditable="true"></div>
Or here's the fiddle: http://jsfiddle.net/tG9Qa/
If you want a different way of solving it other than changing the requirements, with a little display:table it is fully possible =)
.container1 {
height:20px;
width:273px;
overflow:hidden;
border:1px solid green;
}
.container2 {
display:table;
}
.textarea {
width:273px;
font-size: 18px;
font-weight: normal;
line-height: 18px;
outline: none;
display: table-cell;
position: relative;
-webkit-user-select: text;
-moz-user-select: text;
-ms-user-select: text;
user-select: text;
word-wrap: break-word;
overflow:hidden;
}
<div class="container1">
<div class="container2">
<div contenteditable="true" class="textarea"></div>
</div>
</div>
So, for posterity: the simplest solution is to get your product manager to change the requirements so you can do multiline editing. This is what ended up happening in our case.
However, before that happened, I ended up going quite a way in creating a manually moving single-line richtext editor. I wrapped it up in a jQuery plugin in the end. I don't have time to finish it up (there are probably bugs in IE, Firefox works best and Chrome works pretty well - comments are sparse and sometimes not very clear). It uses parts of the Rangy library (extracted because I didn't want to rely on the complete library) to get screen positions of selections in order to test for mouse position vs. selection (so you can drag selections and move the box).
Roughly, it works by using 3 elements. An outer div (the thing you call the plugin on), which gets overflow: hidden, and then 2 levels of nesting inside it. The first level is absolutely positioned, the second level is the actual contenteditable. This separation is necessary because otherwise some browsers will give the contenteditable absolutely positioned element grippies, to let the user move it around...
In any case, then there is a whole bunch of code to move the absolutely positioned element around inside the top element, thus moving the actual contenteditable. The contenteditable itself has white-space nowrap, etc. etc. to force it to stay a single line.
There is also code in the plugin that strips out anything that isn't an image (like br, tables, etc. etc.) from any text that's pasted / dragged into the box. You need some parts of this (like the brs, stripping/normalizing paragraphs, etc.) but maybe you would normally want to keep links, em, strong and/or some other formatting.
Source: https://gist.github.com/1161922
Check out this answer I just posted. This should help you out:
How to create a HTML5 single line contentEditable tab which listens to Enter and Esc
Here is the HTML markup:
<span contenteditable="false"></span>
Here is the jQuery/javascript:
$(document).ready(function() {
$('[contenteditable]').dblclick(function() {
$(this).attr('contenteditable', 'true');
clearSelection();
$(this).trigger('focus');
});
$('[contenteditable]').live('focus', function() {
before = $(this).text();
if($(this).attr('contenteditable') == "true") { $(this).css('border', '1px solid #ffd646'); }
//}).live('paste', function() {
}).live('blur', function() {
$(this).attr('contenteditable', 'false');
$(this).css('border', '1px solid #fafafa');
$(this).text($(this).text().replace(/(\r\n|\n|\r)/gm,""));
if (before != $(this).text()) { $(this).trigger('change'); }
}).live('keyup', function(event) {
// ESC=27, Enter=13
if (event.which == 27) {
$(this).text(before);
$(this).trigger('blur');
} else if (event.which == 13) {
$(this).trigger('blur');
}
});
$('[contenteditable]').live('change', function() {
var $thisText = $(this).text();
//Do something with the new value.
});
});
function clearSelection() {
if ( document.selection ) {
document.selection.empty();
} else if ( window.getSelection ) {
window.getSelection().removeAllRanges();
}
}
Hope this helps someone!!!
You can replace this div with text input (after onclick event is called).
I have used something similar to this plugin and it worked fine.
with jQuery I have set a .keypress event and then tests for e.keyCode == 13 (return key) and if is return false from the event and the editing is not able to make multilines
$('*[contenteditable=yes]').keypress(function(e) {
if(e.keyCode == 13 && !$(this).data('multiline')) {
return false;
}
})

Categories