execCommand h1 style only selected text - javascript

I am working on custom textarea with highlighting options.
Now added h1-h4 & bold options.
Problem:
When I select the text and click on Heading1 button it style the whole row not selected text. When I click on Bold button it style only selected text.
I want to apply h1-h4 style only for selected text instead of whole row.
Here is my code:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<h2>Comment</h2>
<div class="panel panel-default">
<div class="panel-heading">
<button data-command="h1" class="btn btn-default btn-sm">Heading1</button>
<button data-command="h2" class="btn btn-default btn-sm">Heading2</button>
<button data-command="h3" class="btn btn-default btn-sm">Heading3</button>
<button data-command="h4" class="btn btn-default btn-sm">Heading4</button>
<button data-command="bold" class="btn btn-default btn-sm">Bold</button>
</div>
<div class="panel-body" contenteditable>Sample comment</div>
</div>
</div>
</body>
<script>
$(function() {
$(".btn").click(function() {
var command = $(this).data("command");
if (command == 'h1' || command == 'h2' || command == 'h3' || command == 'h4')
document.execCommand('formatBlock', false, '<' + command + '>');
else
document.execCommand(command);
})
})
</script>
</html>

I liked your question. I was not aware of this api. But please next time use ES6(it is everywhere now) and brackets for block expressions.
So from docs
Adds an HTML block-level element around the line containing the current selection, replacing the block element containing the line if one exists (in Firefox, is the exception — it will wrap any containing block element). Requires a tag-name string as a value argument. Virtually all block-level elements can be used.
But you can use insertHTML command.
<!DOCTYPE html />
<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link
rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css"
/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<h2>Comment</h2>
<div class="panel panel-default">
<div class="panel-heading">
<button data-command="h1" class="btn btn-default btn-sm">
Heading1
</button>
<button data-command="h2" class="btn btn-default btn-sm">
Heading2
</button>
<button data-command="h3" class="btn btn-default btn-sm">
Heading3
</button>
<button data-command="h4" class="btn btn-default btn-sm">
Heading4
</button>
<button data-command="bold" class="btn btn-default btn-sm">
Bold
</button>
</div>
<div class="panel-body" contenteditable>Sample comment</div>
</div>
</div>
</body>
<script>
$(function() {
$(".btn").click(function() {
var command = $(this).data("command");
if (
command == "h1" ||
command == "h2" ||
command == "h3" ||
command == "h4"
) {
const selection = window.getSelection();
document.execCommand(
"insertHTML",
false,
`<${command}>${selection}</${command}>`
);
} else {
document.execCommand(command);
}
});
});
</script>
</html>
Also do not forget to serialize you content.

Related

Can't properly animate bootstrap 5 collapse element created via js

My goal is to create a collapse element when the form data has been processed by the server, to notify the user whether the data was successfully sent to the server or an error occurred.
function sendForm(event, form) {
const wrapper=document.createElement('div');
wrapper.setAttribute('role', 'alert');
wrapper.classList.add('alert', 'alert-dismissible', 'alert-success');
wrapper.innerHTML='<span>Success!</span><button type="button" class="btn-close" data-bs-dismiss="alert"></button>';
form.prepend(wrapper);
const bsWrapperCollapse = bootstrap.Collapse.getOrCreateInstance(wrapper);
bsWrapperCollapse.show();
setTimeout(() => {
bsWrapperCollapse.hide();
}, 4000);
setTimeout(() => {
wrapper.remove();
}, 7000);
form.reset();
event.preventDefault();
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-GLhlTQ8iRABdZLl6O3oVMWSktQOp6b7In1Zl3/Jr59b6EGGoI1aFkw7cmDA6j6gD" crossorigin="anonymous">
</head>
<body>
<main class="container-fluid my-5" style="max-width:300px">
<form action="#" method="post" onsubmit="sendForm(event, this)">
<button type="submit" class="btn btn-primary">My form submit btn</button>
</form>
<button class="btn btn-primary" data-bs-toggle="collapse" data-bs-target="#collapseExample" aria-expanded="false" aria-controls="collapseExample">
Button with data-bs-target
</button>
<div class="collapse" id="collapseExample">
<div class="alert alert-dismissible alert-success" role="alert">
<span>Success!</span>
<button type="button" class="btn-close" data-bs-dismiss="alert"></button>
</div>
</div>
</main>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.3.0-alpha1/dist/js/bootstrap.bundle.min.js" integrity="sha384-w76AqPfDkMBDXo30jS1Sgez6pr3x5MlQ1ZAGC+nuZB+EYdgRZgiwxhTBTkF7CXvN" crossorigin="anonymous"></script>
</body>
</html>
I added two implementations to the test html - the first button calls my implementation, which is in the form and when it is pressed, data should be sent, but the animation of appearing and hiding is jerky. The second button is taken from the bootstrap documentation, with the correct animation, which is what I want to achieve in my implementation using js.
I think the problem is that the element created in js haven't the collapse class, the transition is applied only if the element has collapse class. I modified the code , I added the class collapse to the wrapper and added the alerts classes to a div inside the wrapper element.Now it seems the animation works properly
function sendForm(event, form) {
const wrapper=document.createElement('div');
wrapper.setAttribute('role', 'alert');
wrapper.classList.add("collapse");
wrapper.innerHTML='<div class="alert alert-dismissible alert-success"><span>Success!</span><button type="button" class="btn-close" data-bs-dismiss="alert"></button> </div>';
form.prepend(wrapper);
const bsWrapperCollapse = bootstrap.Collapse.getOrCreateInstance(wrapper);
bsWrapperCollapse.show();
setTimeout(() => {
bsWrapperCollapse.hide();
}, 4000);
setTimeout(() => {
wrapper.remove();
}, 7000);
form.reset();
event.preventDefault();
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-GLhlTQ8iRABdZLl6O3oVMWSktQOp6b7In1Zl3/Jr59b6EGGoI1aFkw7cmDA6j6gD" crossorigin="anonymous">
</head>
<body>
<main class="container-fluid my-5" style="max-width:300px">
<form action="#" method="post" onsubmit="sendForm(event, this)">
<button type="submit" class="btn btn-primary">My form submit btn</button>
</form>
<button class="btn btn-primary" data-bs-toggle="collapse" data-bs-target="#collapseExample" aria-expanded="false" aria-controls="collapseExample">
Button with data-bs-target
</button>
<div class="collapse" id="collapseExample">
<div class="alert alert-dismissible alert-success" role="alert">
<span>Success!</span>
<button type="button" class="btn-close" data-bs-dismiss="alert"></button>
</div>
</div>
</main>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.3.0-alpha1/dist/js/bootstrap.bundle.min.js" integrity="sha384-w76AqPfDkMBDXo30jS1Sgez6pr3x5MlQ1ZAGC+nuZB+EYdgRZgiwxhTBTkF7CXvN" crossorigin="anonymous"></script>
</body>
</html>
So, I figured out how I can make the animation normal without even checking the answers here. I noticed that the alert container in the html code is wrapped in another container. But when I created the alert via js, I didn't wrap it. After I wrapped this element, the animation worked as it should. #Nick suggested that the animation doesn't work as expected due to the lack of a collapse class, but I tested his code without it and the animation still works. The reason the animation works correctly is that he wrapped my code in a container via innerHTML, essentially doing the same thing I did. Here's what I ended up with.
function sendForm(event, form) {
const alert=document.createElement('div');
alert.setAttribute('role', 'alert');
alert.classList.add('alert', 'alert-dismissible', 'alert-success');
alert.innerHTML='<span>Success!</span><button type="button" class="btn-close" data-bs-dismiss="alert"></button>';
const alertWrapper=document.createElement('div');
alertWrapper.append(alert);
form.prepend(alertWrapper);
const alertWrapperCollapse = bootstrap.Collapse.getOrCreateInstance(alertWrapper);
alertWrapperCollapse.show();
setTimeout(() => {
alertWrapperCollapse.hide();
}, 4000);
setTimeout(() => {
alertWrapper.remove();
}, 7000);
form.reset();
event.preventDefault();
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-GLhlTQ8iRABdZLl6O3oVMWSktQOp6b7In1Zl3/Jr59b6EGGoI1aFkw7cmDA6j6gD" crossorigin="anonymous">
</head>
<body>
<main class="container-fluid my-5" style="max-width:300px">
<form action="#" method="post" onsubmit="sendForm(event, this)">
<button type="submit" class="btn btn-primary">My form submit btn</button>
</form>
<button class="btn btn-primary" data-bs-toggle="collapse" data-bs-target="#collapseExample" aria-expanded="false" aria-controls="collapseExample">
Button with data-bs-target
</button>
<div class="collapse" id="collapseExample">
<div class="alert alert-dismissible alert-success" role="alert">
<span>Success!</span>
<button type="button" class="btn-close" data-bs-dismiss="alert"></button>
</div>
</div>
</main>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.3.0-alpha1/dist/js/bootstrap.bundle.min.js" integrity="sha384-w76AqPfDkMBDXo30jS1Sgez6pr3x5MlQ1ZAGC+nuZB+EYdgRZgiwxhTBTkF7CXvN" crossorigin="anonymous"></script>
</body>
</html>
Anyway, I marked #Nick's answer as helpful.

Bootstrap tooltip feature not working even after initializing in js

My custom tooltip wasn't displaying at all so I striped my document down to the bare bones and actually plucked an example from the bootstrap website. It still won't work.
https://jsfiddle.net/swagat123/pwzs397b/2/
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Bootstrap demo</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-GLhlTQ8iRABdZLl6O3oVMWSktQOp6b7In1Zl3/Jr59b6EGGoI1aFkw7cmDA6j6gD" crossorigin="anonymous">
</head>
<body>
<script>
const tooltipTriggerList = document.querySelectorAll('[data-bs-toggle="tooltip"]');
const tooltipList = [...tooltipTriggerList].map(tooltipTriggerEl => new bootstrap.Tooltip(tooltipTriggerEl));
// const exampleEl = document.getElementById('example');
// const tooltip = new bootstrap.Tooltip(exampleEl, options);
//Tried this; didn't work:
// $(function () {
// $('[data-toggle="tooltip"]').tooltip()
// })
</script>
<h1>Hello, world!</h1>
<button type="button" class="btn btn-secondary" data-bs-toggle="tooltip" data-bs-placement="top" data-bs-title="Tooltip on top">
Tooltip on top
</button>
<button type="button" class="btn btn-secondary" data-bs-toggle="tooltip" data-bs-placement="right" data-bs-title="Tooltip on right">
Tooltip on right
</button>
<button type="button" class="btn btn-secondary" data-bs-toggle="tooltip" data-bs-placement="bottom" data-bs-title="Tooltip on bottom">
Tooltip on bottom
</button>
<button type="button" class="btn btn-secondary" data-bs-toggle="tooltip" data-bs-placement="left" data-bs-title="Tooltip on left">
Tooltip on left
</button>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.3.0-alpha1/dist/js/bootstrap.bundle.min.js" integrity="sha384-w76AqPfDkMBDXo30jS1Sgez6pr3x5MlQ1ZAGC+nuZB+EYdgRZgiwxhTBTkF7CXvN" crossorigin="anonymous"></script>
</body>
</html>```
Tried bunch of different examples and different ways of initializing to no avail. I need a tooltip to pop up.
The selector is running before the HTML is loaded, so no tooltip elements are found and initialized. If you run it after the window has loaded, it works:
<script>
window.addEventListener('load', function(){
const tooltipTriggerList = document.querySelectorAll('[data-bs-toggle="tooltip"]');
const tooltipList = [...tooltipTriggerList].map(tooltipTriggerEl => new bootstrap.Tooltip(tooltipTriggerEl));
})
</script>
Alternatively, you could move the block to the end of the document.

Uncaught TypeError: screen is null

let screen = document.getElementsByClassName("screen");
let buttons = Array.from(document.getElementsByClassName('calc-button'));
buttons.map(button => {
button.addEventListener('click', (e) => {
switch(e.target.innerText) {
default:
screen.innerText += e.target.innerText;
}
});
});
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
<title>Calculator</title>
<meta charset="UTF-8">
</head>
<body>
<div class="wrapper">
<section class="screen">0</section>
<section class="calc-buttons">
<div class="calc-button-row">
<button class="calc-button">C</button>
<button class="calc-button">←</button>
<button class="calc-button">÷</button>
</div>
<div class="calc-button-row">
<button class="calc-button">7</button>
<button class="calc-button">8</button>
<button class="calc-button">9</button>
<button class="calc-button">×</button>
</div>
<div class="calc-button-row">
<button class="calc-button">4</button>
<button class="calc-button">5</button>
<button class="calc-button">6</button>
<button class="calc-button">−</button>
</div>
<div class="calc-button-row">
<button class="calc-button">1</button>
<button class="calc-button">2</button>
<button class="calc-button">3</button>
<button class="calc-button">&plus;</button>
</div>
<div class="calc-button-row">
<button class="calc-button">0</button>
<button class="calc-button">&equals;</button>
</div>
</section>
</div>
<script src="code.js"></script>
</body>
</html>
When I run that code browser says that variable called "screen" is null.
But I'm tried to check mistakes in the names of variables and ids. But I couldn't find anything, what can be a reason for errors in this code.
Update: I add Html. I haven't element with id "screen", because I had a class with same name, so I changed getElementById to getElementsByClassName. And now is no errors, but It didn't display symbols on the screen.

How do I show div when button is clicked?

This is my CSS code. I want to set the display so that my text whats in the div shows up.
div.divi
{display: none}
This is my HTML code.
<!doctype html>
<html lang="nl">
<head>
<title>Over informatica en ik</title>
<meta charset="utf-8">
<link rel="stylesheet" href="opmaak.css">
</head>
<body>
<div class="divi">
<p class="groot">Informatica</p>
<p>hoi</p>
</div>
<button type="button"
onclick="document.getElementByClass('divi').style.display ='block'">
</button>
</body>
</html>
Try this:
div.divi {
display: none
}
<div class="divi">
<p class="groot">Informatica</p>
<p>hoi</p>
</div>
<button type="button" onclick="document.getElementsByClassName('divi')[0].style.display ='block'; this.style.display = 'none';">
</button>
Tell me if it needs improvement :)
Simply replace <div class="divi"> with <div id="divi"> and the CSS with div#divi{display: none}.
Or if you would prefer to keep divi as a class instead of an ID, you can update your code to the following:
<div class="divi">
<button id="div3">
<p class="groot">Informatica</p>
<p>hoi</p>
</div>
<button type="button" onclick="document.getElementsByClassName('divi')[0].style.display='block'">Text</button>

Can't change div style with JS function

The main goal is to show different divs depending on which button I click, so they all start with the display style at "none" (except a default one called "atualizacoes"). And after I click a button ALL of the divs should be set to
display="none" and after that the one I associated that button with is set to display="block".
However something isn't right because when I click one of the buttons, the default div does disappear however nothing ever appears.
This is how I'm trying to accomplishing it:
In order:
snippet 1 - function I use inside my index.html to change all the
displays
snippet 2 - rule in my stylesheet
snippet 3 - parts of my index.html code (I didn't want to paste
EVERYTHING)
<script type="text/javascript">
function replace(show) {
document.getElementById('default').style.display="none";
document.getElementById('ecra').style.display="none";
document.getElementById(show).syle.display = "block";
}
</script>
.ecra
{
display: none;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<title>University Platform</title>
<!-- Bootstrap core CSS -->
<link href="bootstrap/css/bootstrap.css" rel="stylesheet">
<!-- Custom styles for this template -->
<link href="dashboard.css" rel="stylesheet">
<!-- jquery -->
<script src="assets/js/jquery.min.js"></script>
<script src="bootstrap/js/bootstrap.min.js"></script>
</head>
<body>
<!-- these are the buttons that are located on a sidebar -->
<div class="row">
<h3>Options</h3>
<button type="button" class="btn btn-default botao pull-left" onclick="replace('addestudante')">Adicionar Estudante</button>
</div>
<div class="row">
<button type="button" class="btn btn-default botao pull-left" onclick="replace('adduc')">Adicionar UC</button>
</div>
<!-- these are the divs I want to switch around -->
<div class="row" id='default'>
<p> Hello World </p>
</div>
<!-- in CSS I also made a rule that makes all "ecra" divs be invisible from the start-->
<div class="row ecra" id='addestudante'>
<button type="button" class="btn btn-default"> TEST 1</button>
</div>
<div class="row ecra" id='adduc'>
<button type="button" class="btn btn-default"> TEST 2</button>
</div>
</body>
Why is this function not working properly? Is there something wrong with my code?
There are a couple of issues with what you've written.
For one, you don't have any elements with ID "ecra" — what you want to do is affect all the elements that have the class "ecra". You can do this by looping or mapping over document.getElementsByClassName("ecra").
Secondly, you've misspelt style when you try to show the show element.
Try using this adapted function instead:
function replace(show) {
document.getElementById("default").style.display = "none";
Array.from(document.getElementsByClassName("ecra")).map(element => element.style.display = "none");
document.getElementById(show).style.display = "block";
}
By what I thought, you want to get elements by class name. They're ecra, so you can use querySelectorAll and do a loop for its length. I'll not use getElementsByClassName because it will make the line more longer and return an array.
function replace(show){
var q=document.querySelectorAll('.ecra'),
document.getElementById('default').style.display="none";
for(var i=0,l=q.length;i<l;i++){
!function(i){
q[i].style.display="none"
}(i)
}
document.querySelector('#'+show).style.display = "block"
}
I saw jQuery imported in your page. So I suggest to use jQuery.
<script type="text/javascript">
function replace(show) {
jQuery(function($){
$("#default").css({
"display" : "none"
});
$(".ecra").css({
"display" : "none"
});
$("#"+show).css({
"display" : "block"
});
});
}
</script>
Edited, missing characters.
JS corrected : http://jsfiddle.net/csfd8x35/
.ecra
{
display: none;
}
<!-- these are the buttons that are located on a sidebar -->
<div class="row">
<h3>Options</h3>
<button type="button" class="btn btn-default botao pull-left" onclick="replace1('addestudante')">Adicionar Estudante</button>
</div>
<div class="row">
<button type="button" class="btn btn-default botao pull-left" onclick="replace1('adduc')">Adicionar UC</button>
</div>
<!-- these are the divs I want to switch around -->
<div class="row" id='default'>
<p> Hello World </p>
</div>
<!-- in CSS I also made a rule that makes all "ecra" divs be invisible from the start-->
<div class="row ecra" id='addestudante'>
<button type="button" class="btn btn-default"> TEST 1</button>
</div>
<div class="row ecra" id='adduc'>
<button type="button" class="btn btn-default"> TEST 2</button>
</div>
<script>
function replace1(show) {
document.getElementById('default').style.display="none";
var allByClass = document.getElementsByClassName('ecra');
for (var i=0;i< allByClass.length; i++) {
allByClass[i].style.display = "none";
}
document.getElementById(show).style.display = "block";
}
</script>

Categories