I found a HTML5 way of changing a class of an element using JavaScript.
HTML:
<div id="bootstrap-container" class="container-fluid fill-height">
<!-- Content -->
</div>
JavaScript:
var mql = window.matchMedia('(min-width: 1200px)');
if (mql.matches) {
var containerElement = document.querySelector('#bootstrap-container');
if (containerElement.classList.contains('container-fluid')) {
containerElement.classList.remove('container-fluid');
containerElement.classList.add('container');
}
}
This works fine except there is a noticeable FOUC when loading/refreshing the page.
How can I make the FOUC go away?
When the browser parses your HTML-File, he will execute your JavaScript (either inline or by reference <script src="script.js">) exactly where he found it. Therefore you have 2 possibilities to avoid the mentioned FOUC.
You execute the JavaScript earlier (e.g. as inline javascript right below the element you manipulate the class). It might be a good idea to set only 1 "media query class" (e.g. on the body-tag) and place your corresponding script right below
You hide the content until your JavaScript has been executed. E.g. you could do something like this
HTML
<body class="loading">
...
</body>
CSS
body.loading {
visibility: hidden;
}
JS
var mql = window.matchMedia('(min-width: 1200px)');
if (mql.matches) {
var containerElement = document.querySelector('#bootstrap-container');
if (containerElement.classList.contains('container-fluid')) {
containerElement.classList.remove('container-fluid');
containerElement.classList.add('container');
}
}
document.body.classList.remove("loading")
I solved it by creating a partial view and using bootstraps responsive utility classes hidden-xs, hidden-sm and so on.
I want to achieve a sticky menu like the left navigation on this page: http://getbootstrap.com/2.3.2/scaffolding.html.
My menu is a nav element with position:relative (I tried static as well) that goes fixed when it reaches the top of the viewport.
here's my function:
$(document).ready(function() {
function stickyNav() {
var elementPosition = $('nav').offset();
console.log(elementPosition);
$(window).scroll(function(){
if($(window).scrollTop() > elementPosition.top){
$('nav').addClass("sticky");
} else {
$('nav').removeClass("sticky");
}
});
}
stickyNav();
}); //document ready
the console.log(elementPosition); returns an offset top of around 1200px on page load, which is wrong. But if i resize the page, the value changes to around 650px which is the correct offset top and the function does what it is supposed to be doing.
I've looked around and found out that offsetp top maybe wrong when it's on hidden elements, or it has issues with margins but I actually don't have any complex structure here, just a single visible nav element .
any help on figuring this out would be much appreciated! thanks!!
jQuery(document).ready handler occurs when the DOM is ready. Not when the page is fully rendered.
https://api.jquery.com/ready/
When using scripts that rely on the value of CSS style properties,
it's important to reference external stylesheets or embed style
elements before referencing the scripts.
In cases where code relies on loaded assets (for example, if the
dimensions of an image are required), the code should be placed in a
handler for the load event instead.
So if you're using stylesheets that are loaded AFTER the script in question, or the layout of the page depends on image sizes, or other content, the ready event will be hit when the page is not in its final rendering state.
You can fix that by:
Making sure you include all stylesheets before the script
Making sure the CSS is more robust, and doesn't depend that much on content size (such as images)
Or, you can do this on window load event.
Edit:
If you want to make your script dependent on more than one async event (like the loadCSS library), use this:
var docReady = jQuery.Deferred();
var stylesheet = loadCSS( "path/to/mystylesheet.css" );
var cssReady = jQuery.Deferred();
onloadCSS( stylesheet, function() {
cssReady.resolve();
});
jQuery(document).ready(function($) {
docReady.resolve($);
});
jQuery.when(docReady, cssReady).then(function($) {
//define stickyNav
stickyNav();
});
You can add a check to see if your CSS has loaded by setting a style tag in your document which shows a test element, and then overwrite this in your CSS file to hide it. Then you can check the status of your page by checking this element. For example...
In your HTML:
<div id="loaded-check" style="display:block; height:10px; width:10px; position:fixed;"></div>
In your CSS:
#loaded-check { display:none; }
In your jQuery script:
var startUp = function() {
var cssLoaded = $('#loaded-check').is(':visible');
if (cssLoaded) {
$('#loaded-check').remove();
doOtherStuff()
}
else {
setTimeout(function() {
startUp();
}, 10);
}
}
var doOtherStuff = function () {
//bind your sticky menu and any other functions reliant on DOM load here
}
I am normally used to "window.open" to open a popup window into a new URL. How can open a window into a new URL, shadow out/grey out the current window, and on close remove the shadow background.
Is it best to use jQuery to do this? Could I use the default libraries without use jquery plugins?
I want to do something like this and then "disable" my shadow on unload. Hopefully that uses core jQuery libraries or standard javascript calls. I want to avoid using any plugins besides jQuery.
var popup = window.open('http://google.com', 'popup');
showShadow();
$(window).unload(function() {
if(!popup.closed) {
disableShadow();
}
});
Basically, you can open the popup and set that window the beforeunload. In short, something like this:
popup = window.open("", "name", "width=400, height=300")
popup.onbeforeunload = function() { $('#shadow').hide();}
I created a fiddle for you.
http://jsfiddle.net/DDksS/
So you want to build your own modal box using jQuery instead of using an existing plugin? ...OK, let's play (as it was already pointed out, using popups is not a user-friendly solution):
Your check list :
- the trigger
- the shadow layer
- the modal box size and position
- add content to modal and display it along the shadow
1) The trigger is a simple html link to open the content inside the modal
open url
... we will pass the size of the modal via data-width and data-height (HTML5) attributtes.
2) The shadow layer is the html structure that we will append to the body after the trigger. We can set the structure in a js variable
var shadow = "<div class='shadow'></div>";
3) As we mentioned, the size of the modal is set through some data-* attributes in the link. We would need to do some math
var modalWidth = $(this).data("width");
var modalHeight = $(this).data("height");
var modalX = (($(window).innerWidth()) - modalWidth) / 2; // left position
var modalY = (($(window).innerHeight()) - modalHeight) / 2; // top position
NOTE : $(this) is our trigger selector .myModal that we'll get inside an .on("click") method later on. BTW, the .on() method requires jQuery v1.7+
4) Now we need to create the modal's html structure and pass the content href. We'll create a function
function modal(url) {
return '<div id="modal"><a id="closeModal" title="close" href="javascript:;"><img src="http://findicons.com/files/icons/2212/carpelinx/64/fileclose.png" alt="close" /></a><iframe src="' + url + '"></iframe></div>';
}
... as you can see, our structure contains a close button to remove the modal and the shadow layer. The function also gets a parameter when is called (url) which allows to set the src attribute of the iframe tag.
NOTE : we have to use the iframe tag to open external urls, however we should always consider the same origin policy and other security restrictions when using iframes.
So now, we need to put together all the events after we click on our .myModal trigger, which are appending both the shadow and the modal box to the body and to remove them when we click on the close button so
$(".myModal").on("click", function(e) {
e.preventDefault();
// get size and position
modalWidth = $(this).data("width");
modalHeight = $(this).data("height");
modalX = (($(window).innerWidth()) - modalWidth) / 2;
modalY = (($(window).innerHeight()) - modalHeight) / 2;
// append shadow layer
$(shadow).prependTo("body").css({
"opacity": 0.7
});
// append modal (call modal() and pass url)
$(modal(this.href)).appendTo("body").css({
"top": modalY,
"left": modalX,
"width": modalWidth,
"height": modalHeight
});
// close and remove
$("#closeModal").on("click", function() {
$("#modal, .shadow").remove();
});
}); // on
STYLE : of course we will need some basic CSS style to make our modal elements work properly:
.shadow {width: 100%; height: 100%; position: fixed; background-color: #444; top: 0; left:0; z-index: 400}
#modal {z-index: 500; position: absolute; background: #fff; top: 50px;}
#modal iframe {width: 100%; height: 100%}
#closeModal {position: absolute; top: -15px; right: -15px; font-size: 0.8em; }
#closeModal img {width: 30px; height: 30px;}
* SEE DEMO *
BONUS : you could also bind a keyup event to close the modal using the escape key
$(document).keyup(function(event) {
if (event.keyCode === 27) {
$("#modal, .shadow").remove();
}
}); //keyup
LAST NOTE : the code is subject to many improvements and optimization but is a basic layout of what many lightboxes do. My last recommendation : use fancybox for more advanced functionality ... sometimes it doesn't worth the effort to re-invent the wheel ;)
Using Javascript to create new popup windows is so 1990's, not to mention not very user-friendly. What you're looking for, both UI-wise and looks-wise is a modal dialog; there's billions of examples and pre-packaged jquery snippets on how to create modal dialogs, and most client-side UI frameworks such as jQuery UI, YUI and Bootstrap have modal dialog functionality built-in. I'd recommend diving into those.
Try jquery plugins such as fancybox http://fancybox.net/
Basically, you need to attach an event listener to your new window to run the disableShadow() function in your webpage.
If you add this to your code I think it should work.
popup.unload(function() { disableShadow() });
Adapted From: Attach an onload handler on a window opened by Javascript
You should use the beforeUnload event of the window instance returned by the window.open() call, like this:
popup = window.open('relative_url', 'popup');
$(popup).bind('beforeunload', function() {
disableShadow();
});
Note that the URL must be on the same domain in order for the opener window to interact with the popup!
See the fiddle here: http://jsfiddle.net/hongaar/QCABh/
You can open a new window, and when it closes you can execute a function in the opener window.
I'll do a quick example by writing the script right into the new window, but you could also just include it in the HTML that is used for the new window if a link is supplied for the popup:
$("#popupBtn").on('click', openPopup); //using a button to open popup
function openPopup() {
$('#cover').fadeIn(400);
var left = ($(window).width()/2)-(200/2),
top = ($(window).height()/2)-(150/2),
pop = window.open ("", "popup", "width=400, height=300, top="+top+", left="+left),
html = '<!DOCTYPE html>';
html += '<head>';
html += '<title>My Popup</title>';
html += '<scr'+'ipt type="text/javascript">';
html += 'window.onbeforeunload = function() { window.opener.fadeoutBG(); }';
html += '</sc'+'ript>';
html += '</head>';
html += '<body bgcolor=black>';
html += '<center><b><h2 style="color: #fff;">Welcome to my most excellent popup!</h2></b></center><br><br>';
html += '<center><b><h2 style="color: #fff;">Now close me!</h2></b></center>';
html += '</body></html>';
pop.document.write(html);
}
window.fadeoutBG = function() { //function to call from popup
$('#cover').fadeOut(400);
}
Using a fixed cover that is faded in will also prevent any clicks on elements on the page, and you could even attach a click handler to the cover with pop.close() to close the popup if the cover is clicked, just like a modal would close if you clicked outside it.
One of the advantages of calling a function on the parent page from the popup is that values can be passed from the popup to the parent, and you can do a lot of stuff you otherwise could'nt.
FULLSCREEN_FIDDLE
FIDDLE
All you need is standard javascript function showModalDialog. Then your code will look like
var url = 'http://google.com';
showShadow();
var optionalReturnValue = showModalDialog(url);
//Following code will be executed AFTER you return (close) popup window/dialog
hideShadow();
UPDATE
As hongaar stated Opera does not like showModalDialog. And it does not fire on(before)unload when popup is closed either. To make workaround you need timer (window.setTimeout) to periodically check if window still exists. For further details look here
Why don't you just use jQuery UI? I know that you don't want another library but is rather extension of jQuery rather then another lib since it can live without it.
It have great deal of widget and every one of them can be changed,configured.
What is best that it can viewed with different themes, even you can create one with they're theme roller fast and easy, and it can be modularized. Just take what you need in current project.
Check this out:
http://jqueryui.com/dialog/#modal-form
It's really simple to use. With this you can open modal dialog with frame to different url. On close event you can do whatever you want.
Try ColorBox
its simple and easy to use
http://www.jacklmoore.com/colorbox
quick example:
<link rel="stylesheet" href="http://www.jacklmoore.com/colorbox/example1/colorbox.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script src="http://www.jacklmoore.com/colorbox/colorbox/jquery.colorbox.js"></script>
<script>
$(document).ready(function(){
//Examples of how to assign the ColorBox event to elements
$(".iframe").colorbox({iframe:true, width:"80%", height:"80%"});
});
</script>
<a class='iframe' href="http://google.com">Outside Webpage (Iframe)</a>
You can also try this out ...
http://fancyapps.com/fancybox/
Examples here
try http://thickbox.net/ in modal type, examples: http://thickbox.net/#examples
I've done this as well.
First off, some URLs simply WILL NOT WORK in an (iframe) modal window; I can't say if it'll work in the browser-supported native modal windows as I haven't tried this. Load google or facebook in an iframe, and see what happens.
Second, things like window onunload events don't always fire (as we've seen some people already).
The accepted answer version will also only work on a static page. Any reloading (even F5 on the page) will cause the shadow to hide. Since I can't comment on the accepted answer, I at least wanted this to be known for anyone else looking at these results.
I've taken a less technical approach to solving this problem in the past: polling.
http://jsfiddle.net/N8AqH/
<html>
<head>
<script type="text/javascript">
function openWindow(url)
{
var wnd = window.open(url);
var timer = null;
var poll = function()
{
if(wnd.closed) { alert('not opened'); clearInterval(timer); }
};
timer = setInterval(poll, 1000);
}
</script>
</head>
<body>
click me
</body>
</html>
See the link above for an example. I tested in IE, FF, and Chrome. My timer is every 1 second, but the effort on the browser is so low you could easily drop this down to 100 ms or so if you wanted it to feel more instant.
All you'd have to do in this example is, after calling window.open, call your "show shadow" function and instead of alerting when you close, call your "hide shadow" function and it should achieve what you're looking for.
I've got my mootools FX.slide working fine but I want the content to be hidden at the beginning instead of after they click on the link. I've done this with jquery and I usually just change the class to display:none; but it doesn't work the same with mootools.
How do I go about making the content hidden at first?
Here is a fiddle of what I've made:
http://jsfiddle.net/ajrdesign/seVM7/
Here's the code:
JS
var mySlide = new Fx.Slide('slider_content');
$('toggle').addEvent('click', function(e){
mySlide.toggle();
});
HTML
<li>
<h3>What can I do with Revu iPad?</h3>
<a id="toggle" href="#">Answer</a>
<div id="slider_content">
<p>Revu iPad includes some of the most popular features of Bluebeam Revu, enabling you to redline PDFs and collaborate with others on the go. Access PDFs through Dropbox, Box, iTunes, or WebDAV and redline PDFs with markup tools* including your existing tool sets. Additionally, collaborate with project partners across the globe in real time using Bluebeam Studio. </p>
<p>Revu iPad does not include all the features of Bluebeam Revu. Our app is designed to provide users with the features they need to document issues and collaborate in the field, without compromising speed.</p>
<p>*Measurement annotations are currently not supported.</p>
</div>
</li>
CSS
#slider_content {
padding: 10px;
margin: 20px;
border: 1px solid #e8e8e8;
border-radius: 4px;
}
Found a fix for the problem!
http://jsfiddle.net/ajrdesign/seVM7/1/
Basically added a little domready event:
var mySlide = new Fx.Slide('slider_content');
document.addEvent("domready", function() {
$('slider_content').slide('hide');
$('toggle').addEvent('click', function(e) {
e.stop();
mySlide.toggle();
});
});
I was looking for the same (i.e. setting the default state to 'hidden') and actually the solution is pretty simple and has been described here:
Just add .hide() to your line like so:
var mySlide = new Fx.Slide('slider_content').hide();
Add style="display:none" in HTML code to the element you're going to toggle();
Create Fx.Slide with onComplete callback:
var myFx = new Fx.Slide('slider_content', {
onComplete: function() {
if (this.wrapper.offsetHeight != 0)
this.wrapper.setStyle('height', 'auto');
}
});
Run some code before expanding div for the first time:
var e = $('slider_content');
if ( e.getStyle('display') != 'block' ) {
myFx.hide();
e.setStyle('display', 'block');
}
myFx.toggle();
I'd like to open the page in the image below, but only showing the green part in the new window. Hiding the menu and the header to the user.
function openNewWindow() {
var pr = window.open("Page.aspx", "page", "width=700, height=400");
pr.onload() = function() {
pr.document.getElementById("header").style.display = 'none';
}
}
Is it possible to set some kind of offset for the page in the new window? Like left:-40px and top:-20px or something similar? I know top and left positions the new window rather than its content, but is there something I can do to change the position of the actual content?
Is there a work-around or another solution with the same result?
EDIT
When I click Click I want Page.aspx (image above) to open in a new window, but without menu and header showing.
how about you open a page that shows an iframe which loads your page -- and then you can set your iframe width/height to what you need and whether to provide scrolling or not?
something like this:
<html>
<!-- this is page2.aspx -->
<body>
<!-- header -->
<!-- menu -->
<iframe id="abc"...></iframe>
<script type="text/javascript">
var page = ... //retrieve the value of the parameter "url" passed to us (you can find how to do this by googling)
document.getElementById( "abc" ).src = page; //set the iframe url to the parameter passed
</script>
</body>
</html>
then your function becomes:
function openNewWindow() {
window.open("Page.aspx?url=http://page/to/load", "page", "width=700, height=400");
}
Load the whole page, but hide the header and menu using Javascript:
newwindow.onload = function() {
newwindow.document.getElemementById('header').style.display = 'none';
newwindow.document.getElemementById('menu').style.display = 'none';
}
(or use JQuery's .hide() method)
Load the whole page, but add an extra stylesheet which sets the header and menu to hidden:
#header, #menu {display:none !important;}
when you serve the page, use a different template which doesn't include the header and menu, etc. All things being equal, this would probably be the best option, but I can't really give any advice on this without knowing a whole load more about your code.
(all of the above assumes that you have the IDs in your header and menu that I've specified; change as appropriate)
Agree with Spudley, but if that's not possible you might be able to get by with negative margins. Like this:
body { margin: -50px 0 0 -50px }