How can I show/hide a bootstrap spinner with jQuery? - javascript

I'm trying to show a bootstrap spinner after a click on a button and then hide it after getting a response from an API (basically a loading status).
My button is as follow:
<div class="col-6">
<button type="button" name="btn-enviar" class="btn btn-primary w-100">
<span class="spinner-border spinner-border-sm mr-3" id="spinner" role="status" aria-hidden="true">
</span>Enviar</button>
</div>
So far I've tried to comment/uncomment my span tag with no luck, there would be an easier way to start/stop my spinner?
My comment/uncomment functions which I took from here and are not working (as requested):
function comment(element) {
element.html('<!--' + element.html() + '-->')
}
function uncomment(element) {
element.html(element.html().substring(4, element.html().length - 3))
}

Html (with added class .spinner):
<div class="col-6">
<button type="button" name="btn-enviar" class="btn btn-primary w-100">
<span class="spinner spinner-border spinner-border-sm mr-3" id="spinner" role="status" aria-hidden="true">
</span>Enviar</button>
</div>
Add css to css-file:
#spinner { display:none; }
body.busy .spinner { display:block !important; }
Or use visibility:
#spinner { visibility:hidden; }
body.busy .spinner { visibility:visible !important; }
JQuery:
$(document).ready( function()
{
$('#spinner').on('click', function()
{
$('body').addClass('busy');
});
});
When done, do:
$('body').removeClass('busy');
With a class like 'busy' added to the body of the html page, you can also do very nice things like blocking input elements and such without extra js code. Let CSS do all the work for you instead of js. You only have to add some extra CSS rules.
PS: Check your html for errors with html validator. If there are errors in the markup, strange things might happen or it doesn't work.
Have fun.

There are animation and -webkit-animation css attributes on the element.
Use a class like this
.stop {
animation-name: none !important;
-webkit-animation-name: none !important;
}
With JQuery you can toggle this class on the element. If it is added, the animation will stop.
Update
This will show then hide the spinner.
$(() => {
$('button').on('click', e => {
let spinner = $(e.currentTarget).find('span')
spinner.removeClass('d-none')
setTimeout(_ => spinner.addClass('d-none'), 2000)
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://getbootstrap.com/docs/4.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<link rel="canonical" href="https://getbootstrap.com/docs/4.3/components/spinners/">
<button class="btn btn-primary" type="button">
<span class="d-none spinner-border spinner-border-sm" role="status" aria-hidden="true"></span>
Click me...
</button>

I just faced the same problem and solved it with visibility style attribute.
HTML:
<span class="spinner-border spinner-border-sm" id="spinner" style="visibility: hidden"></span>
JS:
let spinner = document.getElementById("spinner");
spinner.style.visibility = 'visible'; //'hidden'

I didn't get your code exactly but I am putting my idea, you can try if feasible.
$(document).ready(function() {
$("#spinner").spinner({
start: function(event, ui) {
$('#d1').html("Spinner has started ");
},
stop: function(event, ui) {
$('#d1').html("Spinner has stopped ");
}
});
});
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>
<link href="https://code.jquery.com/ui/1.12.1/themes/blitzer/jquery-ui.css" rel="stylesheet">
<input id="spinner" class='selector' value=12 size=3>
<div id=d1></div>

Related

Hide&Show Fieldset on Javascript using a button doesn't work on first click / How to change button title on click

I am trying to hide/sow a fieldset using a button, which works like a charm. However it doesn't wonk when I click the first time, but from the second time on it keeps working ok.
How can I make work the first time I click the button.
Also I'd ike to change the button's title on click too, but I don't know how.
Thanks in advance!
This is the code I have:
$(document).ready(function() {
$('#OcultarEncabezadoFactura').click(function() {
var fieldset = document.getElementById("fsEncabezado");
var boton = document.getElementById("OcultarEncabezadoFactura");
if (boton.textContent== "Ocultar Encabezado") {
$('#fsEncabezado').hide();
boton.textContent= "Mostrar Encabezado";
//title I would like the button to have when fieldset is hidden
} else {
$('#fsEncabezado').show();
boton.textContent= "Ocultar Encabezado";
//title I would like the button to have when fieldset is shown
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button type="button" name="btnOcultarEncabezadoFactura" class="btn btn-xs btn-primary" id="OcultarEncabezadoFactura" data-row-id="0">Ocultar Encabezado</button>
<fieldset id="fsEncabezado"></fieldset>
A button element doesn't have a title property so your test was failing. You need to check the button's textContent.
Also, don't use HTML comment syntax (<!-- comment -->) inside of <script> tags. To comment in JavaScript, it's: // comment here.
$(document).ready(function(){
$('#OcultarEncabezadoFactura').click (function(){
var fieldset = document.getElementById("fsEncabezado");
var boton= document.getElementById("OcultarEncabezadoFactura");
if(boton.textContent =="Ocultar Encabezado"){
fieldset.classList.add('hide');
boton.textContent ="Mostrar Encabezado";
} else {
fieldset.classList.remove('hide');
boton.textContent="Ocultar Encabezado";
}
});
});
.hide { display:none; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button type="button" name="btnOcultarEncabezadoFactura" class="btn btn-xs btn-primary" id="OcultarEncabezadoFactura" data-row-id="0">Ocultar Encabezado</button>
<fieldset id="fsEncabezado"></fieldset>
But, if your goal is to have a button that simply toggles the visibility of the fieldset, just use the element.classList.toggle() API:
$(document).ready(function(){
var fieldset = document.getElementById("fsEncabezado");
$('#OcultarEncabezadoFactura').click (function(){
fieldset.classList.toggle("hide");
});
});
.hide { display:none; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button type="button" name="btnOcultarEncabezadoFactura" class="btn btn-xs btn-primary" id="OcultarEncabezadoFactura" data-row-id="0">Ocultar Encabezado</button>
<fieldset id="fsEncabezado"></fieldset>
You should use innerHTML to change the text on your button, not title.
$(document).ready(function() {
$('#OcultarEncabezadoFactura').click(function() {
var fieldset = document.getElementById("fsEncabezado");
var boton = document.getElementById("OcultarEncabezadoFactura");
if (boton.innerHTML == "Ocultar Encabezado") {
fieldset.classList.add('hide');
boton.innerHTML = "Mostrar Encabezado";
<!-- title I would like the button to have when fieldset is hidden-->
} else {
fieldset.classList.remove('hide');
boton.innerHTML = "Ocultar Encabezado";
<!-- title I would like the button to have when fieldset is shown-->
}
});
});
.hide {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button type="button" name="btnOcultarEncabezadoFactura" class="btn btn-xs btn-primary" id="OcultarEncabezadoFactura" data-row-id="0">Ocultar Encabezado</button>
<fieldset id="fsEncabezado">
<input type="text" />
</fieldset>

Keeping popover active when moving mouse on it with Bootstrap 4.0 and Rails 5.1

I'm using Bootstrap 4.0 with my Rails 5.1 website. I made a popover for user details that trigger at mouse hover, it has website link in it.
<a data-toggle="popover" title="Mini profile" data-content="<%= post.user.location %><%= post.user.website %>">
<%= post.user.fullname %>
</a>
So I need popover to stay on when I move mouse hover the popover itself, so that I can click website link in it. But currently it is disappearing as soon as I move my mouse out if the link. How can I keep it open?
<script type="text/javascript">
$(document).ready(function(){
$('[data-toggle="popover"]').popover({
placement : 'bottom',
trigger : 'hover'
});
});
</script>
Thank you!
Well I quickly created a prototype as below. You need to generate the HTML markup similar to below using Rails and include the JavaScript on your page.
$("[data-toggle=popover]").each(function(i, obj) {
$(this)
.popover({
html: true,
trigger: "manual",
content: function() {
var id = $(this).attr("id");
return $("#popover-content-" + id).html();
}
})
.on("mouseenter", function() {
var _this = this;
$(this).popover("show");
$(".popover").on("mouseleave", function() {
$(_this).popover("hide");
});
})
.on("mouseleave", function() {
var _this = this;
setTimeout(function() {
if (!$(".popover:hover").length) {
$(_this).popover("hide");
}
}, 300);
});
});
.container {padding:20px;}
.form-control {width:120px;}
.popover {max-width:400px;}
#popover-content-logout > * {
background-color:#ff0000 !important;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<div class="container">
<h3>Bootstrap Popover HTML Example</h3>
<a data-toggle="popover" title="Mini Profile" data-container="body" data-placement="right" type="button" data-html="true" href="#" id="info"><span class="glyphicon glyphicon-user" style="margin:3px 0 0 0"></span> Hover Over Me</a>
<div id="popover-content-info" class="hide">
<strong>Pranav</strong><br/>
My Website
</div>
</div>

how to make visible a div which is initially hidden by clicking on button using javascript

I want that my hidden div will be visible continuously after clicking the button.
This is my js code:
document.getElementById("share").onclick=function show(){
document.getElementById("taskdiv2").style.visibility='visible';
};
This is my html code:
<a id="share" onclick="show()" type="button" class="btn btn-lg btn-default" href="">Share</a>
<div id="taskdiv2" style="visibility:hidden" class="row">
hiiiii !this is vivek.
</div>
You have used an anchor tag, so it tries to go to a link unless you prevent default:
document.getElementById("share").onclick=function show(event){
event.preventDefault();
document.getElementById("taskdiv2").style.visibility='visible';
};
Alternatively changing your html anchor to a button will also do the trick, in which case above change is not required:
<button id="share" onclick="show()" type="button" class="btn btn-lg btn-default" href="">Share</button>
It's best to do this using classes as mentioned in above answer by Rayon, if you are going for a better standard of coding. Though based on your requirement I would just add the class to your element, rather than toggle.
Remove inline onclick attribute as you have registered event using JavaScript
Add event.preventDefault() as default behavior of <a> elements is to navigate.
document.getElementById("share").onclick = function(e) {
e.preventDefault();
document.getElementById("taskdiv2").style.visibility = 'visible';
};
<a id="share" type="button" class="btn btn-lg btn-default" href="">Share</a>
<div id="taskdiv2" style="visibility:hidden" class="row">
hiiiii !this is vivek.
</div>
If you are expecting toggle of visibility,
Use Element.classList.toggle
document.getElementById("share").onclick = function show() {
document.getElementById("taskdiv2").classList.toggle('show');
};
.show {
visibility: hidden;
}
<div id="taskdiv2">Content Goes Here!!!</div>
<button id="share">Toggle</button>
function becomevisible() {
document.getElementById("div").style.opacity="1";
}
div {
background:red;
height: 100px;
width: 100px;
opacity: 0;
}
<div id="div">Test</div>
<button onclick="becomevisible()">See the div!</button>
try this one out :
document.getElementById("share").onclick = function show() {
document.getElementById("taskdiv2").classList.toggle('show');
};
.show {
visibility: hidden;
}
<div id="taskdiv2">Content Goes Here!!!</div>
<button id="share">Toggle</button>

JQuery html() does not work with css

I am developing an application, and I need to parse JSON and display it. I used the getJSON() function, which is working fine, and I'm using $(class_name).html(text). When I view the isolated HTML file in the browser, minus the CSS formatting, I can see the text, but when I run the application, and navigate to the page, the text (with the CSS formatting) does not show up. Even when I Inspect the element, the text is not present in it. Why is this happening?
Thank you
What console.log(data); contains:
schools:"Schools"
search-school:"Search school by number or name"
student-det:"Student Details"
students:"Students"
summary:"Summary"
The actual JSON:
{
"schools":"Schools",
"search-school":"Search school by number or name",
"student-det":"Student Details",
"students":"Students",
"summary":"Summary"
}
$.getJSON("./lang/en.json", function(data) {
$(".SecondTopBarTitleProperties").html(data.schools);
});
.SecondTopBarProperties
{
background-color:#333333;
height:40px;
}
.SecondTopBarTitleProperties
{
color:white;
font-size:16px;
margin-top:6px;
margin-left:6px;
font-family: Helvetica;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container SecondTopBarProperties">
<label class="SecondTopBarTitleProperties"></label>
<button data-bind="click:NewSchool" type="button" class=" pull-right btn btn-primary btn-default btn-sm" style="margin-right: 10px;margin-top: 2px; margin-bottom: 2px;">Add School</button>
</div>
Before the "Add School" button, it's supposed to display "Schools".
Plain HTML:
Formatted:
Any help please?
you need to include your styles into your html code i prepared this fiddle
https://jsfiddle.net/vmf3e3mf/4/
$(function(){
var data = { name = "hey" }
$('.SecondTopBarTitleProperties').html('<span style="color:red">'+data.name+'</span>')
})
You need to wait with the execution of your JS until the DOM is ready, else your JS can't manipulate the DOM elements, because they do not yet exist.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$( document ).ready(function() {
// Code inside this block will be executed when the DOM is ready
var data = {
schools: "Schools"
};
$(".SecondTopBarTitleProperties").html(data.schools);
}); // DOM ready
</script>
<div class="container SecondTopBarProperties">
<label class="SecondTopBarTitleProperties">
</label>
<button data-bind="click:NewSchool" type="button" class=" pull-right btn btn-primary btn-default btn-sm" style="margin-right: 10px;margin-top: 2px; margin-bottom: 2px;">Add School</button>
</div>
If this does not work for you, then you need to check what your $.getJSON("./lang / en.json ", function(data) { does, because we can't test this part for you.
Maybe it's due to copy&paste, but it should probably read $.getJSON("./lang/en.json", function(data) { without those spaces.
Check your browser's Network tab (in the browser's console) to see what you're requesting from the server and what the server returns.
I've tried this in w3schools and it works fine.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var data = { name :"hey" };
alert('hi');
$('.SecondTopBarTitleProperties').html(data.name);
});
</script>
</head>
<body>
<div class="container SecondTopBarProperties">
<label class="SecondTopBarTitleProperties"></label>
<button data-bind="click:NewSchool" type="button" class=" pull-right btn btn-primary btn-default btn-sm" style="margin-right: 10px;margin-top: 2px; margin-bottom: 2px;">Add School</button></div>
</body>
</html>

Change class of active bootstrap button on hover

If I want to change the class of this bootstrap button on hover with jQuery, so that the styling of the button changes to the new custom class, that I would like to add with "addClass":
<div id="tile-sort" class="btn-group" data-toggle="buttons">
<label id="sort-hello" class="btn btn-primary btn-xs">
<input type="radio" name="sort-option" value="hello">Hello
</label>
</div>
The below code works:
$('#tile-sort').hover(
function() {
$('.btn-primary').addClass('sort-hover-nonactive');
},
function() {
$('.btn-primary').removeClass('sort-hover-nonactive');
}
);
However, if I attempt to change the class of this "active" bootstrap button on hover with jQuery:
<div id="tile-sort" class="btn-group" data-toggle="buttons">
<label id="sort-goodbye" class="btn btn-primary btn-xs active">
<input type="radio" name="sort-option" value="goodbye">Goodbye
</label>
</div>
The below code does not work:
$('#tile-sort').hover(
function() {
$('.btn-primary.active').addClass('sort-hover-active');
},
function() {
$('.btn-primary.active').removeClass('sort-hover-active');
}
);
Can someone point me in the correct direction for this class adding/removing to happen?
Looks like the issue might be coming from somewhere else, maybe you didn't set !important on your custom css?
I've tried it as follows:
.sort-hover-active {
background-color:red !important;
}
Here is a demo
EDITED:
Following the comments of #jshthornton, I edited the code to be more in line with bootstrap's native code. Here is what I did:
$('#tile-sort').hover(
function() {
$('#sort-goodbye').removeClass('btn-primary').addClass('btn-danger');
},
function() {
$('#sort-goodbye').removeClass('btn-danger').addClass('btn-primary');
}
);
This way you're basically making use of existing bootstrap code instead of applying cumbersome workarounds like !important which should preferably be avoided, if possible.
And here is a demo of that
With js:
.btn-primary.active.sort-hover-active {
background-color:red;
}
Using it like this may be overwritten time to time. If this is the case just find the selector path which has the strongest weight.
http://css-tricks.com/specifics-on-css-specificity/
Without js:
.btn-primary.active:hover {
background-color:red;
}
This is the "best" way to do it if you only need visual changes on hover. This is also the least intensive to the DOM due to less mutations. With this method you can remove your JS hover code.
This also has issues in some legacy IEs. Read more here: css: does every class support :hover state?
Try with toggleClass method and hover event, check this example:
$(document).ready(function(){
$("#my-btn").hover(function(){
$(this).toggleClass("btn-danger");
});
});
<!-- libs -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
<!-- button -->
<a class='btn btn-primary' id='my-btn'>
class change on hover
</a>
If you want to change the text or reuse this logic
, you can create a plugin check this example(toggleBtn plugin):
// pluglin toogleBtn
jQuery.fn.extend({
toggleBtn: function (normalBtnOps, hoverBtnOps) {
var self = this;
self.attr('class', 'btn ' + normalBtnOps.class);
self.text(normalBtnOps.text);
this.hover(function () {
self
.attr('class', 'btn ' + hoverBtnOps.class)
.text(hoverBtnOps.text);
}, function(){
self
.attr('class', 'btn ' + normalBtnOps.class)
.text(normalBtnOps.text);
});
}
});
// test Plugin
$('#my-btn').toggleBtn(
{'class': 'btn-primary','text' : 'normal btn'},
{'class': 'btn-danger','text' : 'hover btn'}
);
$('#my-btn-2').toggleBtn(
{'class': 'btn-warning','text' : 'warning!'},
{'class': 'btn-dark','text' : 'Dark!'}
);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
<a id='my-btn' href='#'></a>
<a id='my-btn-2' href='#'></a>
Good Luck!.

Categories