bugged HTML code editor - javascript

$(document).ready(function() {
var btn = $('.gen');
btn.on('click', function() {
var areaTxt = $('.textarea').val();
var div = $('.result');
div.html(areaTxt);
});
});
.result {
border: 1px solid red;
width: 300px;
height: 150px;
}
.textarea {
width: 300px;
height: 150px;
}
<!DOCTYPE>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<title>Untitled Document</title>
</head>
<body>
<textarea class="textarea"></textarea>
<input type="button" class="gen" value="generate">
<div class="result"></div>
</body>
</html>
I've created a simple HTML code editor. The problem is that when I add style for all classes or divs affect also to my code editor.
I want something like the editor of w3school. Just to show the result in iframe but all code in the textarea to affect only the result area.
http://jsfiddle.net/sederther/4x6dxrs5/

Add to your styles specifically for the box of results would not solve your problem?
.result p {
font-size:8px;
font-family:Georgia;
}
.result h1{
color:red;
font-size:26px;
font-family:Georgia;
}
Like this: http://jsfiddle.net/4x6dxrs5/2/

Check fiddle Here
Just did a few tweaking. Added a dummy attribute to 'textarea' and set a value for that attribute. I then loop through the element and check for the attribute, if found I will reset all the styles applied.
$(document).ready(function() {
var btn = $('.gen');
btn.on('click', function() {
var areaTxt = $('.textarea').val();
var div = $('.result');
div.html(areaTxt);
//Code Addtion
$("textarea").each(function(){
var attr =
$(this).attr('dataref');
if (typeof attr !== typeof undefined && attr !== false && attr == 'source') {
$(this).attr('style', 'background-color: #eee !important');
}
})
});
});
In this case, I am looping all the 'textareas' and check if it has 'dataref' attribute and the value equals source. if so then reset its style. I know it would be tedious to work on all the elements in similar manner, but without using iframe this can be work around.
my 2 cents

Related

Change HTML image source in a div with javascript when click on label not working

I need to change the image inside a div in HTML when clicking a label. I don't think I need to use jquery for that, I want to use just javascript. After some research, it looks simple, all the answers are the same, but I can't get it to work. I know the function when clicking the label works because the label change color, but the image doesn't change and I don't get any syntax error. I'm using chrome. I don't know what I'm doing wrong.
this is HTML/CSS code:
<html>
<body>
<div id="slc_on_label">
<img src=https://ichef.bbci.co.uk/news/800/cpsprodpb/12A9B/production/_111434467_gettyimages-1143489763.jpg>
</div>
<style>
#slc_on_label img {
position:fixed;
width:5.5%;
left:10%;
top:10%;
}
</style>
<label class = "button" id="button" onclick="run(this)">0</label>
<style>
.button {background-color:Powderblue;
font-size: 5vw;
}
</style>
<script src="question.js" ></script>
</body>
</html>
This is the javascript code:
function run(button) {
document.getElementById("slc_on_label").src="https://cdn.pixabay.com/photo/2016/12/13/05/15/puppy-1903313_1280.jpg";
button.style = "background-color:red";
}
You're trying to set the src attribute on <div id="slc_on_label"> instead of the <img> inside it.
You can use document.querySelector() to select the image inside the div:
document.querySelector("#slc_on_label img").src =
"https://cdn.pixabay.com/photo/2016/12/13/05/15/puppy-1903313_1280.jpg";
<html>
<head>
<style>
#slc_on_label img {
position: fixed;
width: 5.5%;
left: 10%;
top: 10%;
}
.button {
background-color: Powderblue;
font-size: 5vw;
}
</style>
</head>
<body>
<div id="slc_on_label">
<img src="https://ichef.bbci.co.uk/news/800/cpsprodpb/12A9B/production/_111434467_gettyimages-1143489763.jpg">
</div>
<label class="button" id="button" onclick="run(this)">0</label>
<script>
function run(button) {
document.querySelector("#slc_on_label img").setAttribute('src', 'https://cdn.pixabay.com/photo/2016/12/13/05/15/puppy-1903313_1280.jpg');
button.style = "background-color:red";
};
</script>
</body>
</html>
function run(button) {
document.querySelector('slc_on_label img').src =
'https://cdn.pixabay.com/photo/2016/12/13/05/15/puppy-1903313_1280.jpg';
button.style.backgroundColor = 'red';
}
Also not breaking the button style.

How can I delete an editable div by clicking on it and then pressing the Delete key on the keyboard with Jquery?

I have a div with the attribute contenteditable = true. I can activate the div content editing by double clicking the div, this is because my div is draggable, so I use the dooble click event to activate the div edition. The fact is that I want to eliminate the complete div by clicking on it and then pressing the Delete key on the keyboard. How can I do that? How can I make it so that when I write something on the div and press the delete key, the entire div will not be deleted? I only want to delete the div when the div edition is not activated, just click on the div and then hit the delete key and voila, it is deleted.
This is my HTML Code:
$(document).ready(function() {
$('.draggable').draggable({
containment: "parent"
});
$(".draggable").resizable();
$('#MyFirstDiv').click(function() {
//HERE I WANT TO PUT THE CODE TO DELETE THE DIV.
});
$("#myContainer").on("dblclick", "#MyFirstDiv", function(e) {
e.preventDefault();
$(".draggable").draggable('disable');
this.querySelector(":scope > :first-child").focus();
});
$("#myContainer").on("blur", "#MyFirstDiv", function(e) {
e.preventDefault();
$(".draggable").draggable('enable');
});
});
#myContainer {
border: 1px solid black;
height: 400px;
width: 100%;
}
#DraggableDiv {
border: 1px solid blue;
}
<!DOCTYPE html>
<html>
<head>
<title>My Delete Div</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>
</head>
<body>
<div id="myContainer">
<div id="MyFirstDiv">
<div class="draggable" contenteditable="true" id="DraggableDiv">
THIS IS MY TEXT INSIDE THE DIV
</div>
</div>
</div>
</body>
</html>
Easiest way to to capture the keydown on the delete key.
$('#MyFirstDiv').click(function(e){
e.preventDefault();
});
$('#MyFirstDiv').keydown(function(e){
e.preventDefault();
if(e.keyCode == 46) {
this.remove();
}
});
You could first just make a variable: divClicked, I store the clicked state of the div
var divClicked = false;
Then in your event listener, update divClicked (it'll be a toggled button):
$("#MyFirstDiv").click(function(e) {
e.preventDefault();
divClicked = !divClicked;
}
Finally, add a delete key event listener like so:
$("#MyFirstDiv").keydown(function(e) {
e.preventDefault();
if (e.keyCode == 46) {
if (divClicked) {
$(this).remove();
} else {
alert("Click the div first then press Delete to remove it");
}
}
})
Full code:
var divClicked = false;
$("#MyFirstDiv").click(function(e) {
e.preventDefault();
divClicked = !divClicked;
}
$("#MyFirstDiv").keydown(function(e) {
e.preventDefault();
if (e.keyCode == 46) {
if (divClicked) {
$(this).remove();
} else {
alert("Click the div first then press Delete to remove it");
}
}
})
It is not advisable to use Delete while the content is being edited. You will want to ensure that the user can click the <div> element itself without editing the content.
Since the <div> is draggable, I would advise using a handle since the click event and keypress events may get capture for content editing and not for your script.
$(function() {
function disDrag(part) {
var drag = part.closest(".draggable");
drag.draggable("disable");
$(".drag-content", drag).removeAttr("contenteditable").blur();
part.toggleClass("ui-icon-locked ui-icon-unlocked");
}
function enDrag(part) {
var drag = part.closest(".draggable");
drag.draggable("enable");
$(".drag-content", drag).attr("contenteditable", true).focus();
part.toggleClass("ui-icon-locked ui-icon-unlocked");
}
function delDrag(part) {
var drag = part.closest(".draggable");
var res = confirm("Are you sure you wish to delete this item?");
if (res) {
drag.remove();
}
}
$('.draggable')
.draggable({
containment: "parent",
handle: ".ui-drag-handle",
start: function() {
$(".ui-drag-handle", this).data("selectable", false);
},
stop: function() {
$(".ui-drag-handle", this).data("selectable", true);
}
})
.resizable();
$(".ui-drag-handle")
.data("selectable", true)
.click(function(e) {
var drag = $(this).closest(".draggable");
if ($(this).data("selectable")) {
drag.toggleClass("drag-selected");
}
});
$(".btn").click(function(e) {
switch (true) {
case $(this).hasClass("ui-icon-unlocked"):
disDrag($(this));
break;
case $(this).hasClass("ui-icon-locked"):
enDrag($(this));
break;
case $(this).hasClass("ui-icon-close"):
delDrag($(this));
break;
}
});
$(document).keyup(function(e) {
if (e.which == 46 && $(".drag-selected").length) {
delDrag($(".drag-selected"));
}
});
});
#myContainer {
border: 1px solid black;
height: 400px;
width: 100%;
}
.draggable {
border: 1px solid blue;
}
.draggable.drag-selected {
border: 1px solid #0f0;
}
.center {
margin-left: 50%;
}
.right {
float: right;
}
.ui-icon.btn {
border: 1px solid #ccc;
border-radius: 3px;
margin-top: 0px;
margin-left: 1px;
}
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>
<div id="myContainer">
<div class="draggable ui-widget" id="DraggableDiv">
<div class="ui-widget-header">
<span class="right ui-icon ui-icon-close btn" title="Delete the item."></span>
<span class="right ui-icon ui-icon-unlocked btn" title="Lock and disable Drag"></span>
<div class="ui-drag-handle" style="width: calc(100% - 42px);">
<span class="center ui-icon ui-icon-grip-dotted-horizontal"></span>
</div>
</div>
<div class="drag-content" contenteditable="true">
THIS IS MY TEXT INSIDE THE DIV
</div>
</div>
</div>
You can see that this is draggable, resizable, and editable. The user can disable drag by clicking the lock icon. If the select the div and click Delete (or key code 46), or they click the close icon, they will be prompted to confirm that they want to delete the item. Once they confirm that Yes they want to, the item is removed.
Since the delete could be triggered by two different ways, I created a delete function.
In regards to structure, you may not be able to get away with such simple HTML structures when dealing with more complex UI interactions. This one <div> element had all sorts of interactions tied to the click event. The user clicks to edit, select, drag... It is better to make more specific targets for some of these events so that you can better script your events.
You could save yourself a lot of time by using Dialog Widget: https://jqueryui.com/dialog/
Hope that helps.
Test
Click on the text to select.
Press D to delete. [sadly delete key didn't work on stack overflow. Simply change the key code in the if statement to change the key from D to DELETE]
Explanation
There are two functions that help solve this problem.Select: Selected the div clicked.EventListener:Listens for the keypress and deletes the selected div.
Select function
Global variable selected stores the information on the div selected.
In select function we are fetching the id name of the div clicked by using currentTarget.id from the event object 'e'.
If statements inside the select function select and deselect the div.
EventListener
Uses event object from the keypress listener to fetch the key pressed.
e.keyCode gives the key. e.which is a fallback. [for ie users]
If they keyCode is 100 (D key), then use the selected variable to get the selected div and change its css display to 'none'.
Additionally there is a else statement, where u can add js to when nothing is selected and the key is pressed.Also the css for class selected is for feedback of when the div is selected.
Here is the code snippet:
let selected;
const select = e => {
//If already selected, this will deselect the div
if(selected == e.currentTarget.id) {
document.getElementById(selected).classList.remove('selected'); //some CSS
selected = null;
} else {
//select this div
selected = e.currentTarget.id;
document.getElementById(selected).classList.add('selected'); //some CSS
}
}
window.addEventListener('keypress', e => {
//Get key pressed
let key = e.keyCode || e.which;
if(selected != undefined) {
if(key == 100) {//If D is pressed
let target = document.getElementById(selected); //get the div
target.style.display = 'none'; //hide div
console.log('deleted: ' + selected);
}
} else {
//Runs if nothing is selected. Do as you please here.
}
})
.selected {
background: black;
color: white;
}
#DraggableDiv {
user-select: none;
cursor: pointer;
font-family: sans-serif;
width: 400px;
text-align: center;
padding: 10px 5px;
}
<!DOCTYPE html>
<html>
<head>
<title>My Delete Div</title>
</head>
<body>
<div id="myContainer">
<div id="MyFirstDiv">
<div id="DraggableDiv" onclick="select(event)">
Click me and press D
</div>
</div>
</div>
</body>
</html>

What's the best way to add an element in an existing class element with basic j.s , jQuery?

Say I had some code in HTML like:
<div id="some_element" class="element_class">
How do I add/create a new div element and add it to the "element_class" with j.s/jQuery?
You can do like this using only javascript
var createDiv = document.createElement('div');
createDiv.textContent='inner div';
document.getElementById('some_element').appendChild(createDiv)
Using Jquery
To add elements at the end
$('#some_element').append("<div>1</div><div>2</div>");
To add element in in the starting
$('#some_element').prepend("<div>1</div><div>2</div>");
Here's a simple solution. Hope it helps!
$(document).ready(function(){
$("#mybutton").click(function () {
if($('.newDiv').length !== 1){
$("#some_element").append("<div class = 'newDiv'>This is a new div</div>");
}
});
});
.newDiv{
height: 80px;
width: 40px;
background: yellow;
border: 1px solid black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<button id = "mybutton">Click me</button>
<div id="some_element" class="element_class">

Prevent children divs from moving while div toggle

I'm new and have I think very simple problem to solve.
I have 4 buttons to show/hide each panel. What should I do to prevent child divs from moving to te left while hiding some div?
I prefer them to stay at the initial position.
This is my code:
HTML:
<button class="panel-button" data-panel="panel1">1</button>
<button class="panel-button" data-panel="panel2">2</button>
<button class="panel-button" data-panel="panel3">3</button>
<button class="panel-button" data-panel="panel4">4</button>
<div class="wrapper">
<div id="panel1">1</div>
<div id="panel2">2</div>
<div id="panel3">3</div>
<div id="panel4">4</div>
</div>
JS:
$(function() {
$('.panel-button').on('click',function(){
var panelId = $(this).data('panel');// attr('data-panel')
$('#'+panelId).toggle();
});
});
CSS:
.wrapper {
overflow: hidden;
width: 420px;
}
.wrapper > div {
width: 100px;
height: 100px;
background: green;
float: left;
margin-left: 5px;
margin-top: 10px
}
Apply css rule opacity = 0; to the div, instead of hiding it.
Like this:
$('.panel-button').on('click',function(){
var pnl = $('#' + $(this).data('panel'));
pnl.css('opacity', pnl.css('opacity') == '0' ? '1' : '0');
});
Solution for clickability issue:
$('.panel-button').on('click',function(){
var pnl = $('#' + $(this).data('panel'));
if(pnl.is(':visible'))
$('<div></div>').appendTo(pnl).width(pnl.width());
else
pnl.next().remove();
pnl.toggle();
});
But still you can use another approach
You can use the visibility property in CSS to achieve this as shown in the below Fiddle link : link
JS Snippet:
$(function() {
$('.panel-button').on('click',function(){
var panelId = $(this).data('panel');// attr('data-panel')
console.log($('#'+panelId).css('visibility'));
if($('#'+panelId).css('visibility') === 'hidden') {
$('#'+panelId).css('visibility','visible');
}
else {
$('#'+panelId).css('visibility','hidden');
}
});
});
The CSS visibility is designed to keep the space a DOM object occupies, but not actually rendering it. Opacity changes its appearance, but not its behavior (eg. still clickable).
So instead of .toggle(), combine visibility with jQuery's .toggleClass():
jsFiddle solution
$(function() {
$('.panel-button').on('click',function(){
var panelId = $(this).data('panel');// attr('data-panel')
$('#'+panelId).toggleClass('hideMe');
});
});

Semantic element to create a toggle and best practice to undo a function

Sample:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Toggle</title>
<style>
#first {
color: blue;
}
#second {
border: 1px solid green;
}
#third {
background: tan;
}
</style>
</head>
<body>
<label for="box">Toggle</label>
<input type="checkbox" id="box" onchange="toggle();">
<div id="first">First</div>
<div id="second">Second</div>
<div id="third">Third</div>
<script>
function toggle() {
var box = document.getElementById('box');
var first = document.getElementById('first');
var second = document.getElementById('second');
var third = document.getElementById('third');
if (box.checked) {
first.style.color = 'red';
second.style.border = '2px dotted blue';
third.style.background = 'olive';
} else {
first.style.color = 'blue';
second.style.border = '1px solid green';
third.style.background = 'tan';
}
}
</script>
</body>
</html>
DEMO
I wonder if an input checkbox is the right element to create a toggle. I also want to know how to undo what I have in the if clause: in else do I have to repeat my stylesheet or is there a shorter neater way to get back to the initial state?
You can do it in better way like this: demo
Add a parent div in html like this:
<div id="parent">
<div id="first">First</div>
<div id="second">Second</div>
<div id="third">Third</div>
</div>
Then handle your front end with css instead inline styling:
.checked #first {
color:red;
}
.checked #second {
border:2px dotted blue;
}
.checked #third {
background:olive;
}
Then add and remove only one class with javascript:
function toggle() {
var box = document.getElementById('box');
var parent = document.getElementById('parent');
if (box.checked) {
parent.className = parent.className + "checked";
} else {
parent.className = "";
}
}
1. I wonder if an input checkbox is the right element to create a toggle?
Definition of toggle*:
COMPUTING a key or command that is operated the same way but with
opposite effect on successive occasions.
Explanation of checkbox**:
In computing, a checkbox (check box, tickbox, or tick box) is a
graphical user interface element (widget) that permits the user to
make a binary choice, i.e. a choice between one of two possible
mutually exclusive options.
So yes, it is the best choice.
2. I also want to know how to undo what I have in the if clause: in else do I have to repeat my stylesheet or is there a shorter neater way to get back to the initial state?
In order to do this you could using jQuery:
Use either addClass()/removeCLass() methods or toggleClass(); You would put your active class stylings into a new class, apply these then simply remove them on the else/off state. This would also mean you maintain the separation between contents and styling.
Or regular JS:
.setAttribute("class", "active"); and .removeAttribute("class", "active"); or simply .removeAttribute("style"); to unset the styles you applied inline and revert to the original state.
*Source
**Source
To answer the second question:
You could use getElementById("id").removeAttribute("style"); to remove inline styles.
if (box.checked) {
first.style.color = 'red';
second.style.border = '2px dotted blue';
third.style.background = 'olive';
} else {
first.removeAttribute("style")
second.removeAttribute("style")
third.removeAttribute("style")
}

Categories