I'm hoping someone has done this before and has some guidance.
I'm using bootstrap on a site, and right now I have a working modal that loads in a set of pictures, currently 2. This works fine and I have them linked with anchor tags.
However, I'm trying to find the best way to take the selection of the image and once the user clicks it, apply it to the background image css for the container.
SO right now I just have a test image for the background, but basically I want the selection of an image from the modal to create a bgImg variable, so to speak, and apply it to the background of my container div in real time. So this should apply some javascript, but I don't really know what specifically to use. Or for that matter, how to create a variable from the selection and then apply it to CSS.
Basically if I select image 1 from the modal, the modal should close and image one's URL should now take the place of the CSS for the background image url, if that makes sense
CSS for the background in question:
.my-container>.middle {
flex-grow: 1;
padding:30px;
background-image: /*this would be the bgImg for the href*/;
background-size: cover;
}
HTML for the modal and the images that I want to apply to the background
Choose Page Background
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Choose an image:</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<img style="width: 200px; height: 200px;" src="images/bg_orange.svg">
<img style="width: 200px; height: 200px;" src="images/bg_green.svg">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
UPDATE:
adding JS
<script type="text/javascript">
const images = document.querySelectorAll('some-image-selector');
images.forEach(img => img.addEventListener('click', setBackground));
function setBackground(e) {
const container = document.querySelector('.my-container > .middle')
container.style.background = `url(${e.target.src}) center center no-repeat`
};
</script>
So to make this work, you'll want to add a click event listener to each image.
const images = document.querySelectorAll('some-image-selector')
images.forEach(img => img.addEventListener('click', setBackground))
something along those lines ^^
Then within setBackground, update the css
function setBackground(e) {
const container = document.querySelector('.my-container > .middle')
container.style.background = `url(${e.target.src}) center center no-repeat`
}
You'll have to do this with Javascript. In jQuery:
//prevent default action
$('.modal-body a').click(function(e) {
e.preventDefault();
});
$('.modal-body img').on('click', function(e){
//store the target url in a variable
let source = $(this).attr('src');
console.log(source);
//set the user-selected image to the proper spot on the page
$('.my-container > .middle').attr('src', source);
//now close the modal
closeModal();
});
function closeModal(){
$('#exampleModal').hide();
}
You can tweak how you want to close the modal by using a function like slideToggle() instead of hide().
I have created a popover so that if I click on the image the popover should appear.
The popover is working. what my main problem is I have inserted buttons in the popover.
so I want to write javascript or jquery code for the button when it is clicked. Can anyone help on this?
I have tried but it's not working!!!!
$(function() {
$('button').click(function() {
var x = $(this).attr('class');
alert(x);
});
});
$(function() {
$("[data-toggle=popover]").popover({
html: true,
container: 'body',
content: function() {
var content = $(this).attr("data-popover-content");
return $(content).children(".popover-body").html();
},
title: function() {
var title = $(this).attr("data-popover-content");
return $(title).children(".popover-heading").html();
},
placement: "auto"
});
});
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="./isobar.js">
</script>
<span>
<img src="./img/more_options_icon.png" data-toggle="popover" tabindex="5" data-trigger="focus" data-popover-content="#moreoptions">
</span>
<div id="moreoptions" class="hidden">
<div class="popover-body">
<div class="list-group">
<button type="button" class="list-group-item"><span class="gap"></span>Edit</button>
<button type="button" class="list-group-item"><span class="gap"></span>Logic Builder</button>
<button type="button" class="list-group-item"><span class="gap"></span>Uneploy</button>
</div>
</div>
</div>
O.k. Here is an updated version of my answer and checked and working code. A secret of a popover is to fire the correspondence function in a right time with a popover firing. So the JS code is:
function firePopover() {
$('.hidden').css('display', 'block');
var delay = 100;
setTimeout(function () {
$('button:not(.main)').unbind('click');
$('button:not(.main)').click(function () {
var x = $(this).attr('class');
alert(x);
$('.hidden').css('display', 'none');
});
}, delay);
}
Here I an using html selector
:not(.main)
to prevent binding and unbinding events to the main button. In addition, we have to pay attention on the fact that every popover rising binds a new event handler to each button. This means that after n popover risings every button will fire it's alert n times. To prevent this effect, it is possible to bind events in the first rising only, or as I did, to unbind an event from a button every popover rising. As to html code, here it is:
<button class="main" onclick="firePopover()">Fire Popover</button>
<div id="moreoptions" class="hidden" hidden>
<div class="popover-body">
<div class="list-group">
<button class="class-0 list-group-item"><span class="gap"></span>Edit</button>
<button class="class-1 list-group-item"><span class="gap"></span>Logic Builder</button>
<button class="class-2 list-group-item"><span class="gap"></span>Uneploy</button>
</div>
</div>
</div>
I only added the ".main" button to accept a simulation, and each button got additional corresponding class "class-0", "class-1", "class-2" for successful demonstration. Now, when you push on the main button, other 3 buttons appear. And to the contrary, pushing on any of those 3 buttons, is following by alert firing and disappearing of all of them. I hope this will help you.
function firePopover() {
$('.hidden').css('display', 'block');
var delay = 100;
setTimeout(function () {
$('button:not(.main)').unbind('click');
$('button:not(.main)').click(function () {
var x = $(this).attr('class');
alert(x);
$('.hidden').css('display', 'none');
});
}, delay);
}
.hidden {
display: none;
}
button {
float: left;
}
.class-0 {
clear: left;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<button class="main" onclick="firePopover()">Fire Popover</button>
<div id="moreoptions" class="hidden" hidden>
<div class="popover-body">
<div class="list-group">
<button class="class-0 list-group-item"><span class="gap"></span>Edit</button>
<button class="class-1 list-group-item"><span class="gap"></span>Logic Builder</button>
<button class="class-2 list-group-item"><span class="gap"></span>Uneploy</button>
</div>
</div>
</div>
I am learning JavaScript. I created a navigation bar with two divs:
And added a function so that when the user scrolls down, the first div will fadeOut:
$(document).ready(function() {
var $nav = $('.first-nav'); //Caching element
// fade in .navbar
$(function() {
$(window).scroll(function() {
// set distance user needs to scroll before we start fadeIn
if ($(this).scrollTop() > 275) {
$nav.fadeOut("fast");
} else {
$nav.fadeIn();
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<nav class="navbar navbar-default navbar-fixed-top pages">
<div class="container-fluid first-nav">
<button id="nav-toggle" data-target=".sidebar-right" data-toggle="sidebar" class="navbar-toggle toggle-right" type="button">
<span></span>
</button>
Login
<button id="get_quote_navbar" name="get_quote_navbar" class="btn btn-login">Get Quote</button>
<i class="fa fa-phone"></i> (877) 400-0232
<!-- Logo -->
<!-- /Logo -->
Home
For Home
For Business
</div>
<div id="navigation" class="col-md-12 sub-nav">
<div class="col-md-6 sub-nav-left">
Commercial
Construction
Multy-family
Partnership
</div>
<div class="col-md-3 sub-nav-right">
<button id="get_quote" name="get_quote_navbar" class="btn btn-quote">Get Quote</button>
</div>
</div>
</nav>
All works fine. In CSS, I created #media for min and max width. And when I do that, for desktop and tablet is all good, but when I want to put fixed first div for mobile, JavaScript makes a problem and I have blinked div when scroll up-down.
How I can add in JS function if (width < 1024) then $nav.fadeIn();?
Try:
if ($(window).width() < 1024) {
$nav.fadeIn();
}
If you want to work with media queries in javaScript, just use the window.matchMedia() as following:
if (window.matchMedia("(min-width: 400px)").matches) {
/* the viewport is at least 400 pixels wide */
} else {
/* the viewport is less than 400 pixels wide */
}
Full reference: https://developer.mozilla.org/en-US/docs/Web/API/Window/matchMedia
To get the effect on resizing the window, you need to do like:
function foo(){
//code here
}
foo();
$(window).on('resize orientationchange',foo);
Thanks guys, I succeeded. This is a code.
$(document).ready(function(){
var $nav = $('.first-nav');//Caching element
// hide .navbar first - you can also do this in css .nav{display:none;}
// fade in .navbar
$(function () {
$(window).scroll(function () {
if ($(this).scrollTop() > 275 && $(window).width() > 1024) {
$nav.fadeOut("fast");
} else {
$nav.fadeIn();
}
});
});
});
you can do like this for test the with of the window,
note: you have to refresh the page when you change the size of the window
var widthScreen = window.matchMedia('(max-width: 1023px)').matches;
if(widthScreen){
$nav.fadeIn();
}
Bootstrap modal hide is not working. Alert comes in else. but my modal is not hidden Added bootply. My issue is the same one.
<button class="button primary" id="buy" data-toggle="modal" data-target=".bs-example-modal-sm" style= "text-decoration:none;" type="button">Review and confirm</button>
<div class="modal-bootstrap fade bs-example-modal-sm" id="myModal" tabindex="-1" role="dialog" aria-labelledby="smallModalLabel" aria-hidden="true">
<div class="modal-bootstrap-dialog modal-sm">
<div class="modal-bootstrap-content">
<div class="modal-bootstrap-body">
-- content ----
</div>
</div>
</div>
<div class="modal-bootstrap-footer">
<button type="submit" class="button primary" data-dismiss="modal">Close</button>
<button type="submit" class="button primary">Save changes</button>
</div>
</div>
<script type="text/javascript">
$("#buy").click(function () {
var a = 4;
if (a == 5) {
alert("if");
$('#myModal').modal('show');
}
else {
alert("else");
$('#myModal').modal('hide');
}
});
</script>
bootply
You are using both modal toggling methods: via Javascript and via data attributes. So your click is firing the modal show as your data attributes set, and your Javascript does not affect this trigger.
Just remove the data attributes and go with the Javascript method:
<button class="button primary" id="buy" style="text-decoration:none;" type="button">Review and confirm</button>
<div class="modal-bootstrap fade bs-example-modal-sm" id="myModal" tabindex="-1" role="dialog" aria-labelledby="smallModalLabel" aria-hidden="true">
<!-- modal contents -->
</div>
<script type="text/javascript">
$("#buy").click(function () {
var a = 4;
if (a == 5) {
alert("if");
$('#myModal').modal('show');
} else {
alert("else");
$('#myModal').modal('hide');
}
});
</script>
I had same problem. Remove fade class.
I had the same problem, tried a lot of things but the only solution that worked for me is #Tang Chanrith suggested to remove individually parts of the modal but a little bit improved to place back and the scrollbar. I'll put my answer just if the accepted answer did not work for them. Sorry for my english. Hope I helped.
#Tang Chanrith
Try this function
function hideModal() {
$("#myModal").removeClass("in");
$(".modal-backdrop").remove();
$("#myModal").hide();
}
Improved Sollution
You just have to delete a class from body and css that generated
function hideModal() {
$("#myModal").removeClass("in");
$(".modal-backdrop").remove();
$('body').removeClass('modal-open');
$('body').css('padding-right', '');
$("#myModal").hide();
}
For those still having issues (hi Googlers!), if you're using fade, you'll have to use javascript to remove fade class.
Try this function
function hideModal(){
$("#myModal").removeClass("in");
$(".modal-backdrop").remove();
$("#myModal").hide();
}
Remove the modal class "fade" will do.
I have solution this problem.
$('#landingpage, body').on('click',function(){
$( ".action-close" ).trigger( "click" );});
try to add return false like this:
$("#buy").click(function () {
var a = 4;
if (a == 5) {
alert("if");
$('#myModal').modal('show');
}
else {
alert("else");
$('#myModal').modal('hide');
}
return false;
});
I checked your code.
Now you compare a == 5. but a is always 4. you may have to check this why you are doing this comparison.
Also you need you remove the data-target if you want to open modal from javascript :
<button class="button primary" id="buy" data-toggle="modal" style="text-decoration:none;" type="button">Review and confirm</button>
data-target directly opening the modal.
Check if this is working.
You should try this $('.modal.in').modal('hide')
Via https://github.com/twbs/bootstrap/issues/489
I had the same problem, my mistake was that I was trying to open the modal window a few times. We must test that the modal window is not already open before trying to open it.
if (!($("#MyModal").data('bs.modal') || {})._isShown){
$("#MyModal").modal('show');
}
Hide modal dialog box using bootstrap
Method 1: using bootstrap
$('.close').click();
$("#MyModal .close").click();
$('#myModalAlert').modal('hide');
Method 2: using stop-propagation
$("a.close").on("click", function(e){
$("#modal").modal("hide");
e.stopPropagation();
});
Method 3: After shown method invoke
$('#myModal').on('shown', function () {
$('#myModal').modal('hide');
})
Method 4: Using CSS
this.display='block'; //Set block css
this.display='none'; //set none css after close dialog
In the java script code you need to add one line of code
$("#savechanges").on("click", function (e) {
$("#userModal").modal("hide");
e.stopPropagation(); //This line would take care of it
});
As I encountered, sometimes you need to remove display style:
style="display: block;"
I had the same issue. I tried the JavaScript way suggested in the post, unfortunately it only worked half of the time. If I triggered my modal a few times, it bugs out. As a result I created a work around using CSS:
/* Hide the back drop*/
.modal-backdrop.show {
display: none;
}
/* Simulate the backdrop using background color */
.modal-open .modal {
background-color: rgba(47, 117, 19, 0.3);
}
I was opening the modal popup when I click on the link using data-toggle="modal" attribute which was bound with that link and trying to close it using javascript but I was failed each time, so when I remove the "data-toggle" attribute and "href" from that link and opened it using javascript then it was closing properly using javascript as well.
from the below few lines of code, you can understand easily
Advanced Search
I changed the above link to something link this
Advanced Search
After that when I try to close it using javascript, then I become successful
$("#CustomerAdvancedModal").modal('hide');
I am also having the same problem, where I can't find the correct solution for it.
Later I observed that what is happening when the modal gets closed when it works well.
Three Main properties are,
modal-open class gets removed from <body> tag.
In <body> tag change CSS .
<div> class of modal-backdrop gets removed.
So, When u do these things manually, you will achieve it, when not works.
The code should be as following in Jquery,
$('body').removeClass('modal-open');
$('body').css('padding-right', '');
$(".modal-backdrop").remove();
$('#myModal').hide();
Hence, try this and get a solution.
Before you open a loading modal, make sure that you close all others.
This is the function is use to close the modal:
function hideLoadingModal() {
$('#loadingModal').on('shown.bs.modal', function () {
$('#loadingModal').modal('hide');
});
}
Now if I want to open the modal I call the above function and open a new one after that.
Like this:
hideLoadingModal();
$('#loadingModal').modal('show');
Hope this helps you.
Cheers
One possible reson should be the order of jquery and bootstrap and your script is not in proper sequence.
Below should be the sequence.
1. <script src='js/jquery-3.2.1.min.js'></script>
2. <script src='js/bootstrap.min.js'></script>
3. your own script:
<script type="text/javascript">
$("#buy").click(function () {
var a = 4;
if (a == 5) {
alert("if");
$('#myModal').modal('show');
}
else {
alert("else");
$('#myModal').modal('hide');
}
});
</script>
Check if you closed all nested div inside main modal div
<div data-backdrop="static" class="modal fade" id="modal-progress" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
-----NESTED DIV ------------------
</div>
None of the above solutions worked for me. If this is your case, try to imitate click event on the close button (the one which is added dynamically):
<div class="modal" tabindex="-1" role="dialog" id="modal" area-hidden="true" style="display: inline-block;">
<div class="modal-dialog modal-dialog-centered" role="document">
...
</div>
Close</div>
</div>
$('.close-modal').click() should resolve the issue.
Try this
give an id to close button
<button type="submit" id="modalcloseBtn" class="button primary" data-dismiss="modal" >Close</button>
and trigger onclick event
$('#modalcloseBtn').trigger("click");
G.modals = [];
/**
*
* #param {
* modalId: string,
* callback: function
* } options
* #returns
*/
const openModal = (options) => {
const {
modalId = false,
callback = () => { }
} = options;
if (!modalId) return;
const modalNode = document.querySelector(`#${modalId}`);
modal = new bootstrap.Modal(modalNode);
modal.show();
const modalObject = {
modal,
id: modalId
};
G.modals.push(modalObject);
callback();
};
/**
*
* #param {
* modalId: string,
* callback: function
* } options
* #returns
*/
const closeModal = (options) => {
const {
modalId = false,
callback = () => { }
} = options;
if (!modalId) return;
const currentModal = G.modals.find(item => item.id === modalId) || false;
if(!currentModal) return;
const { modal } = currentModal;
const { _element, _backdrop } = modal;
_element.classList.remove('show');
_backdrop._element.remove();
G.modals.splice(G.modals.indexOf(currentModal), 1);
callback();
};
openModal({
modalId: 'your-modal-id',
callback: () => {
DoSomethingAfterModalOpened();
}
});
closeModal({
modalId: 'your-modal-id',
callback: () => {
DoSomethingAfterModalClosed();
}
});
if nothing helps (that happens) - make sure that nobody prevents it like below (my case):
$modal.on('hide.bs.modal', function (e) {
if (shouldNotBeClosed) {
return e.preventDefault();
}
});
Same issue here for no reason, i'm not using "fade" stuff.
I open modal and close modal only with js, the hide function is working only when called inside a setTimeout.
<script>
var modal_show = function(){
$("#modal_post").modal("show");
};
var modal_hide = function(){
$("#modal_post").modal("hide");
};
window.addEventListener("message", function(event){
// listening iframe post message
modal_hide();
});
</script>
<div class="modal" id="modal_post" tabindex="-1" role="dialog" style="width: 100%;" data-keyboard="false" data-backdrop="static">
<div class="modal-dialog" style="width: 450px; height:600px; background: white; border: none; box-shadow: none;" role="document">
<div class="modal-content" style="width: 100%; background: white; border: none; box-shadow: none;">
<div class="modal-body" style="width: 100%; background: white; border: none; box-shadow: none; padding: 0;">
<div>
<iframe src="https://perdu.com" style="width:450px;height:600px;"></iframe>
</div>
</div>
</div>
</div>
</div>
For no reason, modal_hide(); is working inside the console but not in my code.
If i replace the modal_hide(); in the event listener with setTimeout(modal_hide, 200); it's working properly
its very easy.. Remove fade class :)
My requirement is that I need to show a modal window as a form to be filled by user. But the height of that modal should be not more then window size.
So if the entries in form are too much then the modal becomes scrollable. The problem is that while validating the entries in the form the error message is shown at the top of the modal above the first entry. If user is at last property then he will not be knowing that some validation error had occurred unless the modal is scrolled to top on the error event.
I have tried :
$(window).scrollTop();
// and
$('#modalId').scrollTop();
this is the modal code:
<div class="modal hide" id="groupModal" tabindex="-1" role="dialog" aria-hidden="true" >
<div class="modal-header">
</div>
<div class="modal-body" style="max-height: 300px;">
<div class="grpForm">
<div class="alert alert-error hide">
<span class="errMsg"></span>
</div>
<div class="alert alert-success hide">
<span class="successMsg"></span>
</div>
<form class = "formFieldHolder" id="groupInfoForm"></form>
</div>
</div>
<div class="modal-footer">
<button class="btn cancelFormBtn" data-dismiss="modal" aria-hidden="true" msgkey="common.cancel.label"></button>
<button class="btn btn-primary submitGroupFormBtn" type="submit" msgkey="common.submit.label"></button>
</div>
</div>
$('#modalId').scrollTop(0);
scrollTop() only returns the value; scrollTop(0) sets the value to 0 (all the way to the top)
To scroll the page to the modal, select html, body and scroll to the offset top of the modal
$("html, body").scrollTop($("#modalId").offset().top);
If you want to scroll the modal div to the top use
$("#modalId").scrollTop(0);
Example on jsFiddle
You can combine both to scroll the page and the modal to a visible area for the user if needed.
References
jQuery scrollTop
jQuery offset
This is a solution without using JQuery, first you get your modal by the id and then, the function scrollIntoView will move to the top of the element you selected, in this case your modal.
let element = document.getElementById('groupModal');
element.scrollIntoView(true);
To avoid rough movement to the top I would prefer to use (animated movement):
$('#modalId').animate({
scrollTop : 0
}, 'slow');
<script type="text/javascript">
$(document).ready(function(){
$('.scroll_top').hide();
$(window).scroll(function(){
if ($(this).scrollTop() > 100) {
$('.scroll_top').fadeIn();
} else {
$('.scroll_top').fadeOut();
}
});
$('.scroll_top').click(function(){
$("html, body").animate({ scrollTop: 0 }, 500);
return false;
});
});
</script>
You have to include "jquery-1.7.1.min.js" file in your page.
http://code.jquery.com/jquery-1.7.1.min.js