CSS Doesn't Work For Submitted Input - javascript

I've decided to try and make a Notes program as a learning experience. The point was to problem-solve on my own, but I'm pretty clueless as to why this won't work.
When I Shift + Double Click a note to rename it the note changes from a <div> to <input>, but the CSS stays the same. When I press enter (which submits the input) the changes back to <div>, and the CSS is there, but it is very small and doesn't take the shape of the text. Any idea why? Thanks!
Code:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
</head>
<body>
<button class="newList" onclick="newNote()">Create a new note</button>
<br></br>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script>
function clickNote(){
if(event.shiftKey){
$( "div" ).click(function() {
$( this ).replaceWith( "<tr><td><form'><input class='rename' placeholder='Type here' onkeydown='enter(event)' id='newListName' autofocus>" + "</input></form></td></tr>" );
});
} else {
location.href='list.html';
}
}
function enter(event){
var enter = event.which;
if (enter == 13){
var input = document.getElementById("newListName");
$( "input" ).keyup(function() {
$( this ).replaceWith( "<tr><td><div class='list' id='list' onclick='clickNote()'>" + input.value + "</div></td></tr>" );
});
}
}
function newNote(){
var newNt = document.createElement("DIV");
var text = "Rename with Shift + Double Click"
newNt.textContent = text;
newNt.setAttribute('class', 'list');
newNt.setAttribute('id', 'list');
newNt.setAttribute("onclick", "clickNote()");
document.body.appendChild(newNt);
}
</script>
</body>
</html>
CSS:
:root {
--main-color: #FFE033;
--secondary-color: #FEC82A;
}
.newList {
height: inherit;
width: 10%;
padding: .4%;
position: relative;
border-bottom: 4px solid var(--secondary-color);
background: var(--main-color);
}
.list {
height: inherit;
width: 10%;
padding: .4%;
position: relative;
border-bottom: 4px solid var(--secondary-color);
background: var(--main-color);
}
.rename {
height: 2.5em;
width: 116%;
padding: .4%;
position: relative;
border-bottom: 4px solid var(--secondary-color);
background: var(--main-color);
}
#list {
cursor: pointer;
}

Am not sure why you are doing this, but you are adding td tr around the div which make it insde a table and create this issue as the width is defined with 10%. Remove it and it should work fine. You need also to correct the input tag.
function clickNote() {
if (event.shiftKey) {
$("div").click(function() {
$(this).replaceWith("<input class='rename' placeholder='Type here' onkeydown='enter(event)' id='newListName' autofocus>");
});
} else {
location.href = 'list.html';
}
}
function enter(event) {
var enter = event.which;
if (enter == 13) {
var input = document.getElementById("newListName");
$("input").keyup(function() {
$(this).replaceWith("<div class='list' id='list' onclick='clickNote()'>" + input.value + "</div>");
});
}
}
function newNote() {
var newNt = document.createElement("DIV");
var text = "Rename with Shift + Double Click"
newNt.textContent = text;
newNt.setAttribute('class', 'list');
newNt.setAttribute('id', 'list');
newNt.setAttribute("onclick", "clickNote()");
document.body.appendChild(newNt);
}
:root {
--main-color: #FFE033;
--secondary-color: #FEC82A;
}
.newList {
height: inherit;
width: 10%;
padding: .4%;
position: relative;
border-bottom: 4px solid var(--secondary-color);
background: var(--main-color);
}
.list {
height: inherit;
width: 10%;
padding: .4%;
position: relative;
border-bottom: 4px solid var(--secondary-color);
background: var(--main-color);
}
.rename {
height: 2.5em;
width: 100%;
padding: .4%;
position: relative;
border-bottom: 4px solid var(--secondary-color);
background: var(--main-color);
}
#list {
cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="newList" onclick="newNote()">Create a new note</button>

Related

Question on element alignment and how cursor is able to stay flush with the text in this editable code textarea?

Looking at this codepen, most of it I grok. But a couple of things I don't understand:
How does the <code> element stay perfectly on top of the <textarea>? I would expect it to be below the textarea looking at the HTML code.
How is the cursor staying so well-aligned with the text such that it functions like the type of cursor in a word document? The cursor even aligns well with the text when I copy and paste the text. Is it the emmet dependency that's helping?
Here is the code:
HTML
<div class="editor-holder">
<ul class="toolbar">
<li><i class="fa fa-indent"></i></li>
<li><i class="fa fa-expand"></i></li>
</ul>
<div class="scroller">
<textarea class="editor allow-tabs"><div class="Editable Textarea">
<h1>This is a fully editable textarea which auto highlights syntax.</h1>
<p>Type or paste any code in here...</p>
<div>
<?php
var simple = "coding";
?>
<script>
with = "Tab or double space functionality";
</script></textarea>
<pre><code class="syntax-highight html"></code></pre>
</div>
</div>
(S)CSS
html, body{
margin: 0;
padding: 0;
height: 100%;
width: 100%;
position: relative;
background: rgb(114, 195, 195);
}
.editor-holder{
width: 800px;
height: 500px;
margin-top: 50px;
border-radius: 3px;
position: relative;
top: 0;
margin-left: -400px;
left: 50%;
background: #1f1f1f !important;
overflow: auto;
box-shadow: 5px 5px 10px 0px rgba(0, 0, 0, 0.4);
transition: all 0.5s ease-in-out;
&.fullscreen{
width: 100%;
height: 100%;
margin: 0;
left: 0;
}
.toolbar{
width: 100%;
list-style: none;
position: absolute;
top: -2px;
margin: 0;
left: 0;
z-index: 3;
padding: 8px;
background: #afafaf;
li{
display: inline-block;
}
a{
line-height: 20px;
background: rgba(144, 144, 144, 0.6);
color: grey;
box-shadow: inset -1px -1px 1px 0px rgba(0,0,0,0.28);
display: block;
border-radius: 3px;
cursor: pointer;
&:hover{
background: rgba(144, 144, 144, 0.8);
}
&.active{
background: rgba(144, 144, 144, 0.8);
box-shadow: none;
}
}
i{
color: #565656;
padding: 8px;
}
}
textarea, code{
width: 100%;
height: auto;
min-height: 450px;
font-size: 14px;
border: 0;
margin: 0;
top: 46px;
left: 0;
padding: 20px !important;
line-height: 21px;
position: absolute;
font-family: Consolas,Liberation Mono,Courier,monospace;
overflow: visible;
transition: all 0.5s ease-in-out;
}
textarea{
background: transparent !important;
z-index: 2;
height: auto;
resize: none;
color: #fff;
text-shadow: 0px 0px 0px rgba(0, 0, 0, 0);
text-fill-color: transparent;
-webkit-text-fill-color: transparent;
&::-webkit-input-placeholder{
color: rgba(255, 255, 255, 1);
}
&:focus{
outline: 0;
border: 0;
-webkit-box-shadow: none;
-moz-box-shadow: none;
box-shadow: none;
}
}
code{
z-index: 1;
}
}
pre {
white-space: pre-wrap;
white-space: -moz-pre-wrap;
white-space: -pre-wrap;
white-space: -o-pre-wrap;
word-wrap: break-word;
code{
background: #1f1f1f !important;
color: #adadad;
.hljs {
color: #a9b7c6;
background: #282b2e;
display: block;
overflow-x: auto;
padding: 0.5em
}
.hljs-number,
.hljs-literal,
.hljs-symbol,
.hljs-bullet {
color: #6897BB
}
.hljs-keyword,
.hljs-selector-tag,
.hljs-deletion {
color: #cc7832
}
.hljs-variable,
.hljs-template-variable,
.hljs-link {
color: #629755
}
.hljs-comment,
.hljs-quote {
color: #808080
}
.hljs-meta {
color: #bbb529
}
.hljs-string,
.hljs-attribute,
.hljs-addition {
color: #6A8759
}
.hljs-section,
.hljs-title,
.hljs-type {
color: #ffc66d
}
.hljs-name,
.hljs-selector-id,
.hljs-selector-class {
color: #e8bf6a
}
.hljs-emphasis {
font-style: italic
}
.hljs-strong {
font-weight: bold
}
}
}
JavaScript
var tabCharacter = " ";
var tabOffset = 2;
$(document).on('click', '#indent', function(e){
e.preventDefault();
var self = $(this);
self.toggleClass('active');
if(self.hasClass('active'))
{
tabCharacter = "\t";
tabOffset = 1;
}
else
{
tabCharacter = " ";
tabOffset = 2;
}
})
$(document).on('click', '#fullscreen', function(e){
e.preventDefault();
var self = $(this);
self.toggleClass('active');
self.parents('.editor-holder').toggleClass('fullscreen');
});
/*------------------------------------------
Render existing code
------------------------------------------*/
$(document).on('ready', function(){
hightlightSyntax();
emmet.require('textarea').setup({
pretty_break: true,
use_tab: true
});
});
/*------------------------------------------
Capture text updates
------------------------------------------*/
$(document).on('ready load keyup keydown change', '.editor', function(){
correctTextareaHight(this);
hightlightSyntax();
});
/*------------------------------------------
Resize textarea based on content
------------------------------------------*/
function correctTextareaHight(element)
{
var self = $(element),
outerHeight = self.outerHeight(),
innerHeight = self.prop('scrollHeight'),
borderTop = parseFloat(self.css("borderTopWidth")),
borderBottom = parseFloat(self.css("borderBottomWidth")),
combinedScrollHeight = innerHeight + borderTop + borderBottom;
if(outerHeight < combinedScrollHeight )
{
self.height(combinedScrollHeight);
}
}
// function correctTextareaHight(element){
// while($(element).outerHeight() < element.scrollHeight + parseFloat($(element).css("borderTopWidth")) + parseFloat($(element).css("borderBottomWidth"))) {
// $(element).height($(element).height()+1);
// };
// }
/*------------------------------------------
Run syntax hightlighter
------------------------------------------*/
function hightlightSyntax(){
var me = $('.editor');
var content = me.val();
var codeHolder = $('code');
var escaped = escapeHtml(content);
codeHolder.html(escaped);
$('.syntax-highight').each(function(i, block) {
hljs.highlightBlock(block);
});
}
/*------------------------------------------
String html characters
------------------------------------------*/
function escapeHtml(unsafe) {
return unsafe
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, """)
.replace(/'/g, "'");
}
/*------------------------------------------
Enable tabs in textarea
------------------------------------------*/
$(document).delegate('.allow-tabs', 'keydown', function(e) {
var keyCode = e.keyCode || e.which;
if (keyCode == 9) {
e.preventDefault();
var start = $(this).get(0).selectionStart;
var end = $(this).get(0).selectionEnd;
// set textarea value to: text before caret + tab + text after caret
$(this).val($(this).val().substring(0, start)
+ tabCharacter
+ $(this).val().substring(end));
// put caret at right position again
$(this).get(0).selectionStart =
$(this).get(0).selectionEnd = start + tabOffset;
}
});
How does code and textarea elements stay aligned?
They are aligned because in the CSS they both use the same style which outlines the positioning of both elements. They both use position: absolute and the same top and left properties so stay in the same position.
See here https://www.w3schools.com/css/css_positioning.asp
In terms of the z-axis you can see that code has a z-index of 1 while textarea has 2 so text area stays on top.
How is the cursor staying aligned with the text?
There is no javascript acting on the cursor here. If you were to have any textarea in html the cursor would align with the text.

Javascript - I have two event listeners which run the same global scope function, but one of them isn't working...why?

For a bit of context, I'm currently new to Javascript and programming in general. I'm currently making a to-do list using vanilla javascript.
I want the user to be able to add an entry by either clicking on the "+" button, or by pressing the enter key in the input field.
Definitions:
let count = 0;
let getAdd = document.getElementById('add')
let getBackground = document.getElementById('background')
let getInputs = document.getElementsByClassName('input')
let getItems = document.getElementsByClassName('item')
let getName = document.getElementById('name')
The "keypress" event listener is working, but the "click" event listener is not. Here's the part in question:
function addevent() {
if (document.getElementById('name').value === '') {
alert("You need to type something in the input field first!")
return
}
if (getItems.length == 0) {
count += 1;
getBackground.innerHTML = ''
getBackground.style = null;
getBackground.innerHTML += '<div class="item"><div class="column input"></div><div id="spacer" class="column"></div><div id="bin" class="bin column row">X</div></div>'
getInputs[count - 1].innerHTML = document.getElementById('name').value
let heightplus = getBackground.offsetHeight;
getBackground.style.height = parseInt(heightplus + 35) + "px"
document.getElementById('name').value = ''
}
else {
count += 1
getBackground.innerHTML += '<div class="item"><div class="column input"></div><div id="spacer" class="column"></div><div id="bin" class="bin column row">X</div></div>'
getInputs[count - 1].innerHTML = document.getElementById('name').value
let heightplus = getBackground.offsetHeight;
getBackground.style.height = parseInt(heightplus + 35) + "px"
document.getElementById('name').value = ''
}
}
getAdd.addEventListener("click", addevent(), false);
getName.addEventListener("keypress", function enter(e) {
if (e.keyCode === 13) {
addevent();
}
}, false);
What am I missing here?
If you need any further info, let me know.
let count = 0;
let getAdd = document.getElementById('add')
let getBackground = document.getElementById('background')
let getInputs = document.getElementsByClassName('input')
let getItems = document.getElementsByClassName('item')
let getName = document.getElementById('name')
function noitems() {
if (count == 0) {
getBackground.innerHTML = '<div class="start">Click on the <strong>+</strong> button to get started</div>'
}
else if (count == -1) {
getBackground.innerHTML = '<div class="end">No more tasks? Happy days!</div>'
count += 1
}
getBackground.style.paddingTop = "0px"
getBackground.style.boxShadow = "0px 0px 0px 0px"
getBackground.style.backgroundColor = "white"
}
window.onload = noitems();
function addevent() {
if (document.getElementById('name').value === '') {
alert("You need to type something in the input field first!")
return
}
if (getItems.length == 0) {
count += 1;
getBackground.innerHTML = ''
getBackground.style = null;
getBackground.innerHTML += '<div class="item"><div class="column input"></div><div id="spacer" class="column"></div><div id="bin" class="bin column row">X</div></div>'
getInputs[count - 1].innerHTML = document.getElementById('name').value
let heightplus = getBackground.offsetHeight;
getBackground.style.height = parseInt(heightplus + 35) + "px"
document.getElementById('name').value = ''
}
else {
count += 1
getBackground.innerHTML += '<div class="item"><div class="column input"></div><div id="spacer" class="column"></div><div id="bin" class="bin column row">X</div></div>'
getInputs[count - 1].innerHTML = document.getElementById('name').value
let heightplus = getBackground.offsetHeight;
getBackground.style.height = parseInt(heightplus + 35) + "px"
document.getElementById('name').value = ''
}
}
getAdd.addEventListener("click", addevent(), false);
getName.addEventListener("keypress", function enter(e) {
if (e.keyCode === 13) {
addevent();
}
}, false);
function doSomething(e) {
if (e.target.id === "bin") {
if (getItems.length == 1) {
let clickeditem = e.target
getBackground.removeChild(clickeditem.parentNode)
count -= 2
noitems();
}
else {
let clickeditem = e.target
getBackground.removeChild(clickeditem.parentNode)
let heightminus = getBackground.offsetHeight;
getBackground.style.height = parseInt(heightminus - 75) + "px"
count -= 1
}
}
e.stopPropagation();
}
getBackground.addEventListener("click", doSomething, false)
#import url('https://fonts.googleapis.com/css2?family=Roboto:wght#100&display=swap');
body {
font-family: 'Roboto', sans-serif;
-webkit-touch-callout: none; /* iOS Safari */
-webkit-user-select: none; /* Safari */
-khtml-user-select: none; /* Konqueror HTML */
-moz-user-select: none; /* Old versions of Firefox */
-ms-user-select: none; /* Internet Explorer/Edge */
user-select: none; /* Non-prefixed version, currently
supported by Chrome, Opera and Firefox */
}
#title {
font-size: 32px;
margin-top: 1em;
border: 5px;
border-style: solid;
border-color: #001F5F;
width: 9em;
margin-left: calc(50% - 4.6em);
margin-right: calc(50% - 4.5em);
text-align: center;
}
#inputfield {
overflow: hidden;
padding-top: 5px;
padding-bottom: 5px;
margin-top: 50px;
margin-bottom: 10px;
}
::placeholder {
color: #E7E6E6;
opacity: 0.8;
}
#name {
height: 35px;
width: 813px;
outline: none;
background-color: #001F5F;
color: #E7E6E6;
text-align: left;
vertical-align: middle;
font-size: 22px;
box-shadow: 1px 2px 4px 2px darkgray;
margin-right: 10px;
border: 5px;
border-color: #E7E6E6;
float: left;
border-radius: 5px 5px 5px 5px;
}
#add {
height: 35px;
width: 35px;
background-color: #E7E6E6;
color: #001F5F;
font-size: 32px;
font-style: bold;
text-align: center;
vertical-align: middle;
line-height: 35px;
cursor: pointer;
box-shadow: 1px 2px 4px 2px darkgray;
float: left;
border-radius: 5px 5px 5px 5px;
}
#add:hover {
background-color:#001F5F;
color: #E7E6E6;
}
#background {
box-shadow: 0px 2px 4px 2px darkgray;
width: 900px;
height: 0px;
background-color: #E7E6E6;
padding-top: 20px;
border-radius: 5px 5px 5px 5px;
}
.start, .end {
text-align: center;
margin-top: 250px;
font-size: 32px;
padding: 0px;
vertical-align: middle;
}
#spacer {
width: 10px;
height: 35px;
background-color:#E7E6E6;
}
.input {
height: 35px;
width: 808px;
background-color:#001F5F;
padding-left: 5px;
border: 0px;
font-size: 22px;
color: #E7E6E6;
text-align: left;
vertical-align: middle;
outline: none;
box-shadow: 0px 2px 4px 2px darkgray;
border-radius: 5px 5px 5px 5px;
}
.bin {
width: 35px;
height: 35px;
font-size: 24px;
font-style: normal;
background-color: #E7E6E6;
color:#001F5F;
text-align: center;
vertical-align: middle;
line-height: 35px;
cursor: pointer;
border-radius: 5px 5px 5px 5px;
}
.bin:hover {
background-color:#001F5F;
color: #E7E6E6;
box-shadow: 0px 2px 4px 2px darkgray;
}
.item {
margin-left: 32px;
display: table;
table-layout: fixed;
width: 858px;
margin-bottom: 20px;
}
.column {
display: table-cell;
}
.thelist {
margin-left: calc(50% - 450px);
}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Oliver's To-Do List</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<h1 id="title">Oliver's To-Do List</h1>
<body>
<div class="thelist">
<div id="inputfield">
<input type="text" placeholder="Start typing here..."id="name">
<div id="add">+</div>
</div>
<div id="background">
</div>
</div>
<script src="main.js"></script>
</body>
</html>
Thanks!
getAdd.addEventListener("click", addevent(), false);
should be
getAdd.addEventListener("click", addevent, false);
As per this example from https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener :
// Function to change the content of t2
function modifyText() {
const t2 = document.getElementById("t2");
if (t2.firstChild.nodeValue == "three") {
t2.firstChild.nodeValue = "two";
} else {
t2.firstChild.nodeValue = "three";
}
}
// Add event listener to table
const el = document.getElementById("outside");
el.addEventListener("click", modifyText, false);
Ok so I found out that within the getAdd event listener, the problem was the pair of brackets after the function name; once these are removed, it works just fine!
If anyone reading wants to add to this with their wisdom, knowledge and experience, or perhaps suggest any other improvements, please do!
Thanks!
Oh, you solved it. I just tried it out and modified something in the index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Oliver's To-Do List</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<h1 id="title">Oliver's To-Do List</h1>
<body>
<div class="thelist">
<div id="inputfield">
<input type="text" placeholder="Start typing here..."id="name">
<div id="add" onclick="addevent()">+</div>
</div>
<div id="background">
</div>
</div>
<script src="main.js"></script>
</body>
</html>
I added onclick="addevent()" , and It works

Javascript Pop up no longer shows on webpage

So I have a pop up that originally showed on every webpage. After some modification to include the use of cookies to stop the webpage loading every single session, the pop up no longer shows. I can't figure out why and after extensive testing, research and just straight up asking for help I've concluded I do not have enough of an understanding on the subject.
If anyone is able to help me understand why its not working and help with a solution.
<div id='popup' style="display:none">
<div class='cnt223'>
<h1>Important Notice</h1>
<p>
Test!
<br />
<br />
OK
KO
</p>
</div>
</div>
<script>
function setCookie(cname, cvalue) {
window.document.cookie = cname + "=" + cvalue;
}
function getCookie(cname) {
var ca = decodeURIComponent(document.cookie).split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i].trim().split('=');
if (cname == c[0] && c.length > 1) {
return c[1];
}
}
return "";
}
function checkCookie() {
if (getCookie("ageverification") == "") {
$('#popup').show();
$('#popup a.close').click(function ( event ) {
event.preventDefault();
$('#popup').hide();
setCookie("ageverification", 'true');
});
$('#popup a.goBack').click(function ( event ) {
event.preventDefault();
goBack();
});
} else {
return null;
}
}
function goBack() {
window.history.go(-2);
}
checkCookie();
CSS "This is just on the same HTML page for now"
<style type="text/css">
#overlay {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: #000;
filter:alpha(opacity=70);
-moz-opacity:0.7;
-khtml-opacity: 0.7;
opacity: 0.7;
z-index: 100;
display: none;
}
.cnt223 a{
text-decoration: none;
}
.popup{
width: 100%;
margin: 0 auto;
display: none;
position: fixed;
z-index: 101;
}
.cnt223{
min-width: 600px;
width: 600px;
min-height: 150px;
margin: 100px auto;
background: #f3f3f3;
position: relative;
z-index: 103;
padding: 15px 35px;
border-radius: 5px;
box-shadow: 0 2px 5px #000;
}
.cnt223 p{
clear: both;
color: #555555;
/* text-align: justify; */
font-size: 20px;
font-family: sans-serif;
}
.cnt223 p a{
color: #d91900;
font-weight: bold;
}
.cnt223 .x{
float: right;
height: 35px;
left: 22px;
position: relative;
top: -25px;
width: 34px;
}
.cnt223 .x:hover{
cursor: pointer;
}
</style>
Is the element with id "popup" nested within (a child of) the element with id "overlay" ? If it is, the element with id "overlay" has got display:none; , meaning the popup might be displaying, but it's parent is not. Try replacing:
$('#popup').show();
with:
$('#popup, #overlay').show();
Another problem could be that the Javascript is executed before the browser added the element with id "popup" to it's DOM. Try replacing:
checkCookie();
with:
$(function () { checkCookie(); });

Unable to print output in specific div?

First of all I am not very good in designing but with some help I am able to acheive this code
My main issue is that when a user opens a div it becomes the target div, so if I have five divs open at the same time it doesn't matter which I type in because the text gets appended to the last opened div. I can also open an unlimited amount of the same div, which should not happen.
The small issue I have is that I'm unable to close the div and minimize it(much like fb when we click on the chat box it gets minimized).
Fiddle
HTML
<div id="contact">
<header>Users</header>
<main>
<ul>
<li id="Prashant">Prashant</li>
<li id="Katrina">Katrina</li>
<li id="Priyanka">Priyanka</li>
<li id="Kareena">Kareena</li>
<li id="Anushka">Anushka</li>
</ul>
</main>
</div>
<div id="chat"></div>
CSS
* {
-webkit-box-sizing: border-box; /* Safari/Chrome, other WebKit */
-moz-box-sizing: border-box; /* Firefox, other Gecko */
box-sizing: border-box; /* Opera/IE 8+ */
}
body{margin:0;padding:0;}
#contact {
height: auto;
background: #ececec;
position:absolute;
right:0;
bottom:0;
width:100px;
}
#contact header {
padding: 10px;
background: #333;
color: #FFF;
}
#contact main {
padding: 10px
}
#chat {
position: fixed;
bottom: 0;
left: 0;
right: 100px;
height: auto;
}
#chat .user {
border: 1px solid #333;
background: #fff;
width: 200px;
height: 100%;
float: left;
margin-right: 5px;
}
.user header {
position: relative;
background: #4b67a8;
border: 1px solid #2e4588;
}
.user header .status {
position: absolute;
top: 36%;
left: 10px;
width: 8px;
height: 8px;
-webkit-border-radius: 4px;
-moz-border-radius: 4px;
border-radius: 4px;
background: green;
}
.user header .header-text {
color: #fff;
font-weight: bold;
padding: 8px;
margin: 0 0 0 15px;
font-size: 12px;
text-shadow: 0 -1px rgba(0, 0, 0, .25);
}
.user header .close {
position: absolute;
right: 5px;
top: 7px;
color: #fff;
}
.message-area {
background: #fff;
height: 120px;
padding: 5px;
color: #333;
overflow: scroll;
}
.user .input-area {
border-top: 1px solid #333;
padding: 3px;
}
.user .input-area input {
padding: 5px;
width: 100%;
font-size: 12px;
border: none;
outline: none;
}
Javascript
var username = 'user201';
$(document).ready(function() {
$('a').click(function(e) {
e.preventDefault();
var targetUser = ($(this).html());
$(document).data('chat.targetUser', targetUser);
var user = '<div class="user open" id="' + targetUser + '"><header><div class="status"></div><div class="header-text">' + targetUser + '</div><div class="close">×</div></header><div class="message-area"></div><div class="input-area"><input type="text" id="input" /></div></div>';
$('#chat').append(user);
});
$('#chat').on('keydown', '#input', function(event) {
if (event.keyCode == 13) {
var targetUser = $(document).data('chat.targetUser');
var txt = $(this).val();
$('#' + targetUser + ' .message-area').append(username + ': ' + txt + '<br/>');
$(this).val('');
}
});
});
I edited div.close and added a div.mini like
<div class="mini" title="MINIMIZE">-</div>
<div class="close" title="CLOSE">×</div>
Css for .mini
.user header .mini {
position: absolute;
right: 25px;
top: 7px;
color: #fff;
cursor:pointer;
}
JS code for them to work
$(document).on("click", "div.close", function(){
$(this).parent().parent().remove();
});
$(document).on("click", "div.mini", function(){
var elem = $(this).parent().parent().children().not("header");
elem.slideToggle();
});
Also added this js code to prevent add the div if it's already opened and make it append to last section of chat
if ($("div#" + targetUser).length > 0) {
$("div#" + targetUser).appendTo("#chat");
return false;
}
FIDDLE
EDIT
Edited div.mini click function for -/+ Minimize/Maximize
$(document).on("click", "div.mini", function(){
var elem = $(this).parent().parent().children().not("header");
elem.slideToggle();
$(this).text($(this).text() == "-" ? "+" : "-");
$(this).attr("title", $(this).attr("title") == "MINIMIZE" ? "MAXIMIZE" : "MINIMIZE");
});
UPDATED FIDDLE
The text you enter will appear in the last opened div because your var targetUser is changed every time you click on one of the users. The best way to solve this I think is to find the parent of the input field and search for the previous .message-area.
Like this:
$('#chat').on('keydown', '#input', function(event) {
if (event.keyCode == 13) {
var txt = $(this).val();
$(this).parent().prev(".message-area").append(username + ': ' + txt + '<br/>');
$(this).val('');
}
});
Working JSFiddle
Here is the fix for your code:
http://jsfiddle.net/afzaal_ahmad_zeeshan/36pcu/14/
I have updated the code in your fiddle, and I have added a fix so that the divs don't open up twice.
I just added a class to the link of the user, to show that this user is now active. Here is the code
if($(this).attr('class') != 'active') {
var targetUser = ($(this).html());
$(document).data('chat.targetUser', targetUser);
var user = '<div class="user open" id="' + targetUser + '"><header><div class="status"></div><div class="header-text">' + targetUser + '</div><div class="close">×</div></header><div class="message-area"></div><div class="input-area"><input type="text" id="input" /></div></div>';
$('#chat').append(user);
}
$(this).attr('class', 'active');
Then the div thing was handled using this code:
if (event.keyCode == 13) {
var txt = $(this).val();
$(this).parent().prev(".message-area").append(username + ': ' + txt + '<br/>');
$(this).val('');
}
This was the fix for your code, now it works.
According to your statement "...Also I am able to open an unlimited amount of the same divs, which should not happen**..." this can be prevented if you know what are the boxes opened
please check the Fiddle
var id = '#Box' + targetUser;
var existent = $('#chat').find(id)[0];
// This will ensure that you can only open one box at each time
if(existent != null){
alert('There is already one chat to user "' + targetUser + '" open');
}
else
{
your code...
}
Also the fix proposed by speetje33 helps you prevent to write always in the last box.
I've added some comments to the code for your better understanding.

How to restrict drag (disable) in the block?

How to restrict drag (disable) in the block?
Full example
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function(){
var x = 0, setElementMove = 0, getElementMove = $('#drag');
getElementMove.mousedown(function(event){
x = event.clientX+$(document.body).position().left-parseInt($(this).css('left'));
setElementMove = true;
if(typeof event.preventDefault != 'undefined'){
event.preventDefault();
return false;
}
});
getElementMove.ondragstart = function(){
return false;
};
$(document).mouseup(function(){
setElementMove = false;
});
$(document).mousemove(function(event){
if(setElementMove){
getElementMove.css('left', event.clientX+$(document.body).position().left-x + 'px');
}
});
});
</script>
<h1>How to restrict drag (disable) in the block?</h1>
<div id="block">
<div id="border">
<div id="drag" style="left:200px;">some text</div>
</div>
</div>
<style type='text/css'>
h1, #drag {
font: bold 1.0em arial, helvetica, tahoma, verdana, sans-serif;
margin: 10px 0px;
text-align: center;
}
#block {
border: 1px solid #DDD;
overflow: hidden;
width: 100%;
}
#border {
border: 1px solid red;
margin: 0px auto;
overflow: hidden;
width: 70%; /*important*/
height: 150px;
}
#drag {
background: #DDD;
cursor: default;
position: absolute;
top: 50px;
width: 54px;
height: 45px;
}
</style>
edit your mousemove like this,
$(document).mousemove(function(event) {
var eleft = event.clientX + $(document.body).position().left - x;
if (eleft > boundary.offset().left && (eleft + getElementMove.width() < boundary.offset().left + boundary.width() ) ) {
if (setElementMove) {
getElementMove.css('left', eleft + 'px');
}
}
});
crazy demo
Since you asked for jQuery (altough you are using Mootools in your example), have a look at jQuery Ui Draggable. They have IMO the best drag & drop utility you can have with jQuery.

Categories

Resources