Can't change div style with JS function - javascript

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>

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.

How to hide Bootstrap 5 modal on button click

I have a Bootstrap 5 modal, which is used to download a file by clicking a button. This works fine, but I want the modal to be hidden after clicking the download button, and this is where I'm struggling.
I am attempting to use jQuery to do this. I know that the jQuery library is successfully imported and that my function is being executed because I can display an alert box within the same function, but I can't get the modal to hide.
The full code snippet is pasted below with the script section at the bottom. The key line of code that I am trying to use to dismiss the modal is: -
$('#downloadConfirm1').modal({show : false});
I have also tried the following: -
$('.modal.in').modal('hide');
But neither has worked. I am extremely grateful to anyone who takes the time to read my post. Any suggestions most welcome!
<!DOCTYPE html>
<html>
<head lang="en">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<title>Java Documentum Services</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.1.3/js/bootstrap.min.js" integrity="sha512-OvBgP9A2JBgiRad/mM36mkzXSXaJE9BEIENnVEmeZdITvwT09xnxLtT4twkCa8m/loMbPHsvPl0T8lRGVBwjlQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.1.3/css/bootstrap.min.css" integrity="sha512-GQGU0fMMi238uA+a/bdWJfpUGKUkBdgfFdgBm72SUQ6BeyWjoY/ton0tEjH+OSH9iP4Dfh+7HM0I9f5eR0L/4w==" crossorigin="anonymous" referrerpolicy="no-referrer" />
</head>
<body>
<div class="container">
<a class="btn btn-sm btn-outline-primary" data-bs-toggle="modal"
data-bs-target="#downloadConfirm1"
role="button">Download
</a>
<div class="modal fade" id="downloadConfirm1" tabindex="-1" aria-labelledby="downloadConfirm1"
aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="downloadModalLabel">Confirm download</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal"
aria-label="Close"></button>
</div>
<div class="modal-body">
<p>Download Docx_test_file.docx?</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
<a href="files/dummy.pdf" download="dummy.pdf">
<button type="button" id="download_button1">Download</button>
</a>
</div>
</div>
</div>
</div>
</div>
</body>
<script>
$('#download_button1').click(function() {
alert("Hello! I am an alert box!!");
$('#downloadConfirm1').modal({show : false});
});
</script>
</html>
Bootstrap 5 modal dropped jQuery so that is why you cannot hide the modal with jQuery. You should save your modal instance in the moment of initialization.
Afterwards you can use this code to hide your modal.
Ref: Bootstrap 5 Modal#hide
var modalInstance = new bootstrap.Modal(document.getElementById('downloadConfirm1'));
var modal = document.getElementById('downloadConfirm1');
modalInstance.hide(modal);
var myModalEl = document.querySelector('#scheduleMeetingModal');
var myModal = bootstrap.Modal.getOrCreateInstance(myModalEl);
myModal.hide();

execCommand h1 style only selected text

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.

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>

bootstrap modal button click event not fired on first time

i am new to twitter bootstrap .i am using the bootstrap 3
and this is my html code
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Bootstrap Samples</title>
<script src="scripts/jquery1.10.2.min.js"></script>
<script src="bootstrap-3.1.1-dist/js/bootstrap.min.js"></script>
<link rel="stylesheet" type="text/css" href="bootstrap-3.1.1-dist/css/bootstrap.min.css" />
<link rel="stylesheet" type="text/css" href="bootstrap-3.1.1-dist/css/bootstrap-theme.min.css" />
<style>
.banner {color:#FF0000;}
</style>
<script>
$(document).ready(function(){
$("#MyModal5").on('hidden.bs.modal',function(){
$("#btnYes").on('click',function(e){
var $myMod = $(this);
var id = $myMod.data('cust-id');
if(id=='y'){
alert("You clicked yes button");
}
});
});
});
</script>
</head>
<body>
<!-- -------------------------------------------------------------------- -->
<div class="modal fade" id="MyModal5">
<div class="modal-dialog modal-sm">
<div class="modal-content">
<div class="modal-title">
<label style="color:#FF6600;">Confirmation</label>
</div>
<div class="modal-header">
<button class="close" data-dismiss="modal">×</button>
</div>
<div class="modal-body">
<label>This may cause to make an additional hit to server. Are you sure you want to continue ?</label>
</div>
<div class="modal-footer">
<button class="btn btn-success btn-sm" id="btnYes" data-cust-id="y" data-dismiss="modal">Yes</button>
<button class="btn btn-danger btn-sm" id="btnNo" data-cust-id="n" data-dismiss="modal">No</button>
</div>
</div>
</div>
</div>
<!-- -------------------------------------------------------------------- -->
<div class="container">
<div class="row">
<div class="col-sm-12">
<label>If you want to visit google</label>Click here
</div>
</div>
</div>
</body>
</html>
idea is that i have a link, while i click on that link i need to populate the model.its working,now if i click on the 'yes' button on that modal ,i need an alert, but problem is that alert is not showing when i click on yes button for first time ,but if i again click on that button for second time it is showing,another problem is tht if i clicked on third time alert is showing twise,i dont know the exact reason,i suspect this is because of the on event of jquery.
can any one help me to slove this issue
I believe the issue may stem from your click event bindings being nested. Try removing the outer binding and just register the click event in this way:
$(document).ready(function() {
$("#btnYes").on("click",function(e) {
var $myMod = $(this).closest(".modal"); // Select on closest parent modal
// Now run your required code
});
});
});
Hope this works and helps! Good luck.

Categories