Use Javascript to Change Display Styles (CSS) Without Affecting Print Styles - javascript

I have a web application that utilizes a separate print stylesheet to control how the page looks when it comes out of the printer. That was working wonderfully until I recently made some Javascript enhancements to the site. One of these enhancements allows the user to freeze the page header and navigation, as well as table headers. The Javascript behind this does some CSS trickery to freeze the elements on the screen. Unfortunately, applying position: fixed to my header (for example) causes it to print on every page, and this is not a desired effect. How can I use Javascript to tweak element styles on the client-side without affecting the print style?
#media print { #foo { color: blue; } } /* Print definition */
#media screen { #foo { color: green; } } /* Display definition */
document.getElementById('foo').style.color = 'red'; /* Overrides both! */

Instead of changing properties on your elements with this:
document.getElementById('foo').style.color = 'red';
append a new <style> element, for example:
$('<style>#media screen { #foo { color: green; } }</style>').appendTo('head');
It would be better to concatenate all your required changes into one <style> element, if possible.

Add !important to your print rules.

You can try this
#media print { #foo { color: blue !important; } }
The problem is that javascript .style.something, edits the inline css of the element, therefore it will override the normal css class/id rules.
Or you can, work with classes.
document.getElementById('foo').className = 'redText';
and keep the .redText in your regular css file (not the print one), much much better than filling your print css with !important rules.

No good solution! What I ended up doing is utilizing the onbeforeprint and onafterprint functions in IE (I am in the position here that we only have IE users) to "unfreeze" and "refreeze" the elements...
window.onbeforeprint = function() {
document.getElementById('foo').style.position = 'static';
}
window.onload = window.onafterprint = function() {
var el = document.getElementById('foo');
// Get element position and size
// Set left/top/width/height properties
// Set position to fixed
el.style.position = 'fixed';
}

The proper solution is not to poke styles onto nodes, but to instead tie your screen-specific style tweaks to css classes that only affect your screen rendition of things:
#media screen { .freeze { position: fixed; } } /* Display-only definition */
+
document.getElementById('foo').className = "freeze";
As a bonus, this also makes it easy to change tons of styles with just one line of js, which makes things faster and easier to maintain, too.

Related

Run JS function only on screen (not print)?

I have a DIV with long text and truncate it with a function. That is all good, until someone will print the page. The truncated text won't be readable.
Is there some way I can prevent it?
I have looked for an equivalent for CSS's media print, but all I can find works with screen width. I don't know what is better: to truncate only on for media screen or to remove the truncation on 'print'.
// Truncate the job description
$(function() {
if ( $('#jetsSearch').length ) {
$('.job-description').readmore({
speed: 100,
collapsedHeight: 50,
moreLink: 'Read more',
lessLink: 'Less',
});
}
});
I tried this one, but it doesn't work (still truncated)
if ( $('#jetsSearch').length && window.matchMedia("screen").matches) {
It looks like you're using the readmore.js jquery plugin.
This is how I've handled the exact same issue. Readmore.js uses javascript to apply an inline style of height (among other things) to your container. The only way to override those inline styles in your CSS it to use the !important rule in your declaration.
So by adding height: auto; to elements with the data attribute of data-readmore with the important rule, you can override this for print styles (I use a print media query in my CSS for this). I also hide the "read more" link because it's irrelevant to printed pages.
#media print {
[data-readmore] {
height: auto !important;
}
[data-readmore-toggle] {
display: none !important;
}
}

Animation in jQuery works on desktop but not in mobile

I have an animation that triggers when the page load and it is an image going from right to left, very straightforward. Now, it works very well on desktop but not so good in mobile. Is there any way to apply something like a media queries as it is done with css but for jQuery?
You can actually try to combine CSS media queries and JS, by using a hidden element and setting a specific value for some CSS property like z-index. You can then check the value of this property with JS and set a mobile variable accordingly.
I've found that this works more accurate than trying to get the viewport width in JS. Or at least it makes sure that the point at which the variable is true in JS is exactly the same as when the changes to the CSS occur.
CSS
#test {
display: none;
z-index: 1;
}
#media only screen and (max-width: 400px) {
#test {
z-index: 2;
}
}
JS
(function($) {
var $test,
isMobile = false;
function checkTest() {
if ($test.length) {
isMobile = $test.css('z-index')=='2';
}
}
$(function() {
$test = $('#test');
checkTest();
});
$(window).on('resize',function() {
checkTest();
});
// in the rest of your code you can now simply check if isMobile is true
})(jQuery);
Edit
Preferably you should not be using an extra hidden element just for this purpose. You should usually have some existing element that is altered in some way by the media query and you can check for that. Like a header that is fixed in desktop view but not for mobile, or perhaps a logo that is 200px wide for desktop and only 100px for mobile. You get the idea.

CSS Hover being de-activated

I am displaying a page of thumbnails, which if you hover over them, their description is displayed.
for this I am using a span element with CSS
.thumb:hover .thumbText {
display: inline-block ;
}
This works fine initially.
But as this needs to work on a touch device and touch does not have hover, I added a button to show all descriptions.
This also works fine, but once I have used the Button Toggle, Description my javascript function has somehow disabled the CSS hover and I can not work out why.
var CaptionsOff = true;
function toggleCaptions() {
if (CaptionsOff) {
/* Turn Captions ON */
$('.thumbText').css("display", "inline-block")
$("#btnCaption").html("Hide Thumb Captions");
CaptionsOff = false;
} else {
/* Turn Captions OFF */
$('.thumbText').css("display", "none")
$("#btnCaption").html("Show Thumb Captions");
CaptionsOff = true;
}
The site is
http://mclportal.net/wcit/June26.html
That Javascript code adds the CSS to a style attribute on the element. For example:
<span style="display:none">Caption</span>
Style attributes take priority over CSS files. To change this, modify your CSS script like this:
.thumb:hover .thumbText {
display: inline-block !important;
}
This code means that the display from the CSS is used, rather than from the attribute.
Also, you are missing semicolons.
Hope this helps.
Alternatives:
Toggle a class
$(".buttonCaption").toogleClass("showCap")
.thumb:hover .thumbText, .showCap {
display: inline-block;
}
Set the display to nothing, rather than none. Assumes that the captions are have display:none as default in CSS. Other two solutions are probably better than this.
$('.thumbText').css("display", "");
Add !important to your class rule. The .css() method adds the style to element's "style" attribute which has higher priority.
.thumb:hover .thumbText {
display: inline-block!important ;
}
Setting inline style to $('.thumbText') in toggleCaptions() overrides the stylesheet. Toggle a class instead of setting inline styles.
add this in else with your code::$('.thumbText').removeAttr("style");

Can I use JQuery with inline html? If so how?

I learned html and css a week ago. I completed my first project only to find that a div tag I used was not resizing to mobile formats. I have done some research and it seems the answer may reside with JQuery or .JS. I am working within a contained environment, Wordpress.com, and I don't know Java Script yet, but I am familiar with if then statements from studying logic for years.
So I effectively have two problems:
Can I use JQuery with inline html: no css?
How do I do it?
I know I am way off here. I am in the process of going through a .JS tutorial on codeacademy, but I am not finished.
Just thought I would try for advice here. I may not even be in the ballpark!
Here is my div tag and here is what I attempted:
<div style="width:950px;height:5px;background-color:#FFFFFF;"></div>
$(window).resize(function() {
if ($(this).width() < 951) {
$('.divIWantedToHide').hide(<div style="width:950px;height:5px;background-color:#FFFFFF;"></div>);
} else {
$('.divIWantedToHide').show(<div style="width:450px;height:5px;background-color:#FFFFFF;"></div>);
}
});
Javascript is kind of over-kill for this kind of thing.
I would suggest using CSS media queries.
Paste this in and it should work just fine :)
<style>
#YourDiv{
height:5px;
background-color:#FFFFFF;
}
#media only screen and (min-width:951px){
#YourDiv{width:950px;}
}
#media only screen and (max-width:950px){
#YourDiv{width:450px;}
}
</style>
<div id="YourDiv"></div>
Instead of having your style defined in the div tag, your div now has a unique name (an id) that can be styled separately. This is incredibly useful, and most would argue necessary, once you start building more complicated pages. The #media tags do basically the same thing as your if statements, where min-width:951px will set the style when your window is AT LEAST 951px and max-width:950px sets the style when your window is AT MOST 950px. The rest of the styles that don't change are set above ONE time because they are the same regardless of window size.
And now, just for fun I'll show you how to do it in pure Javascript as well:
http://jsfiddle.net/AfKU9/1/ (test it out by changing the preview window size)
<script>
var myDiv = document.getElementById("myDiv");
window.onresize = function(){
var w = window.innerWidth;
if (w > 600){
myDiv.setAttribute("style",'position:absolute;height:50px;background-color:#CCC;width:400px;' )
}
else{
myDiv.setAttribute("style", 'position:absolute;height:50px;background-color:#333;width:100px;' )
}
}
</script>
$('.divIWantedToHide').hide() will hide the div !!
In order to apply css to this div you need to use css:
$('.divIWantedToHide').css('width':'950px','height':'5px','background-color':'#FFFFFF');
If you want to append any div and apply css to it then use append/html
$('.divIWantedToHide').append('<div style="width:950px;height:5px;background-color:#FFFFFF;"></div>');
or
$('.divIWantedToHide').html('<div style="width:950px;height:5px;background-color:#FFFFFF;"></div>');
No, at wordpress.com you won't be able to use inline JavaScript. Not in regular posts using the HTML editor nor using the Custom Design upgrade that only includes a CSS editor.
Maybe you'll benefit from the following:
Preprocessor
WordPress.com has support for CSS preprocessors LESS and Sass (SCSS Syntax). This is an advanced option for users who wish to take advantage of CSS extensions like variables and mixins. See the LESS and Sass websites for more information. You can select which syntax you would prefer to use at the bottom of the Appearance -> Customize -> CSS panel.
If you want to resize or apply another style to some elements adapted to the device screen size, yout can just use the #media css property.
#your_div_id {
width: 950px;
/* ... */
}
#media (max-width: 38em) {
#your_div_id {
display:none;
}
}
You are trying to hide a div with class '.divIWantedToHide'. But your div does not have any class.
So you should add to your div the class:
<div class="divIWantedToHide" style="width:950px;height:5px;background-color:#FFFFFF;"> </div>
And then, you can show and hide it like here:
$(".divIWantedToHide").hide()
$(".divIWantedToHide").show()

Tiny scrollbar doesn't work with javascript (javascript conflict)

I'm using tiny scrollbar for my new website www.digimobjobs.com
I'm using this scrollbar in many places, but this webste is the only place that has a scrollbar problem.
This is where: http://www.digimobjobs.com/news.php.
At the twitter tab and news tab, I have to put a specific scroll height:
#newsWidget
{
font-weight:lighter;
font-size:12px;
height:2000px;
color:#333333;
text-align:left;
}
#twitter-ticker{
width:610px;
/* height:921px; */
height:1025px;
color:#4297f9;
/* display:none; */
text-align:left;
}
In the rest of the places I'm using the same code of the tiny scrollbar. I think the conflict is between javascript. Actually I don't have enough knowledge of javascript.
Could any one help me please? If you use firebug you can see my entire code.
Please help me!
I have tested your site with Google Chrome and Firefox and I don't see any problem.
Extra
However, if you are still having problems on yours, you might want to consider changing the scrollbar using CSS3.
Learn more:
Surfin' Safari Blog (harder to understand)
CSS-Tricks* (easier to understand)
In conclusion, it is basically working like this: (From the CSS-Tricks site)
::-webkit-scrollbar { /* CSS here */ } /*the whole scrollbar*/
::-webkit-scrollbar-button { /* CSS here */ } /*the scrollbar buttons*/
::-webkit-scrollbar-track { /* CSS here */ } /*the scrollbar's whole track*/
::-webkit-scrollbar-track-piece { /* CSS here */ } /*the scrollbar's track*/
::-webkit-scrollbar-thumb { /* CSS here */ } /*the scrollbar's moving piece*/
::-webkit-scrollbar-corner { /* CSS here */ } /*bottom corner piece (when no resize)*/
::-webkit-resizer { /* CSS here */ } /*bottom corner piece (when there's resizing)*/
Update
I have done a few testing, and I fixed the second tab:
// Try running this in the console when it the page is completely loaded.
$("#news_feed").tinyscrollbar();
$("#news_feed").tinyscrollbar_update();
According to the Tiny Scrollbar site, it said,
The update (.tinyscrollbar_update()) method can be used for adjusting a scrollbar to its new content.
So you will have to call it every time you change the content. For example, your XML updating needs to call it every time.
But why the problem is happening?
After a few testing, it seems like the api runs before your content is loaded.
As a result, it thought that the two <div>s are empty and has no height (so no scrollbar for you).
The first Twitter tab?
Try to fix it by yourself.
I have never used this plugin before, so I might be wrong. Fix me if you see a mistake.
Please Re Init tinyScroller bar by this mathod.
$('#scrollbar1').tinyscrollbar_update();

Categories

Resources