Jquery change background size AND image src - javascript

I'm trying to change both background-image and background-size (so it fits the div)
$(".clickableimg").click(function() {
var choosenpic = $(this).attr('id');
$("#image").val(choosenpic);
$("#preview").css("background","url(backgrounds/"+choosenpic+")");
$("#preview").css("background","size('50%')");
});
Do you know how I can change more css attributes?

Setting the background style twice overwrites it, so only the last one will stick, you'll need to use valid CSS properties, like background-image and background-size to change them seperately :
$(".clickableimg").on('click', function() {
var choosenpic = this.id;
$("#image").val(choosenpic);
$("#preview").css({
'background-image' : 'url(backgrounds/'+choosenpic+')',
'background-size' : '50%'
});
});

I'm not entirely sure that your code works correctly because I think you mean
$("#preview").css("background-image","url(backgrounds/"+choosenpic+")");
but if what you have works already then cheers.
You can change any css attributes as long as its supported by the browser.
$("#preview").css("display", "none")
$("#preview").css("width", "5000px")
$("#preview").css("text-shadow", "...")
$("#preview").css("box-shadow", "...")
$("#preview").css("border", "...") ..
I can go on and on..but here is a list of some of CSS3 properties you can play with
http://www.quackit.com/css/css3/properties/

First of all if you're new to javascript you should first look at how javascript basically works before starting with a framework like jQuery. According to your question the following jquery plugin should help you to accomplish your task:
https://github.com/louisremi/background-size-polyfill
This plugin will help you get it working in IE8 too.

Related

addClass(); jQuery Function Not Working in Firefox

I have a script that picks a random background image for the body element of my document from a directory called bg-images. If the chosen background image has "_dark" in the image file name, I would like to add a special class to the body element.
Here is the jQuery I'm using. It works great in Chrome & Safari, but does nothing in Firefox:
var backgroundImage = $('body').css('background');
var isitdark = "_dark";
if (backgroundImage.indexOf( isitdark ) != -1 ) {
$('body').addClass("dark");
} else {
$('body').removeClass("dark");
}
How come this doesn't do anything in Firefox? Is there a better way of writing it?
I've tried adding "type=text/javascript" to all my script tags but that doesn't seem to help and the rest of the jQuery on my site works correctly in all browsers.
You're not getting the background image with $('body').css('background'); Use .css('background-image')
var backgroundImage = $('body').css('background-image');
It's not necessary because the string _dark will or will not be there but if you want to you can remove the url() or url("")
var backgroundImage = /url\(\s*(['"]?)(.*?)\1\s*\)/g.exec($('body').css('background-image'))[2];
Works fine in FF
http://jsfiddle.net/mNX3A/
background is a shorthand property. Shorthand properties are not guaranteed to be retrieved correctly with css:
Retrieval of shorthand CSS properties (e.g., margin, background, border), although functional with some browsers, is not guaranteed.
If you specifically want to get background-image, get background-image:
var backgroundImage = $('body').css('background-image');

Change text color based on background color?

I've a pretty minimalistic site, so I want to add details to it, like a hidden theme switching. But I don't want to tell the user that the theme can be changed, so I want to hide the text.
I've tried this:
var tausta = $(body).css("background-color");
$('.piiloteksti').css("color",tausta);
But it doesn't do anything. What would be the correct approach?
A fiddle.
if($('.piiloteksti').css("color",tausta); is a wrong statement. Thats a syntax error! There shouldn't be any if here.
Either remove if
$('.piiloteksti').css("color",tausta);
or complete the if statement.
if($('.piiloteksti').css("color",tausta)){
// some other code
}
Also $(body) does not refer to anything. Use either $('body') or $(document.body)
I tried to modify CSS, and it works.
// javascript
var tausta = $('body').css("background-color");
if($('.piiloteksti').css("color") == tausta) {
alert(tausta);
}
// css (test)
body{background-color:red;}
.piiloteksti{color:red;}
The syntax of your the if statement was off a little. Also, body must be made a String literal.
var tausta = $("body").css("background-color");
$('.piiloteksti').css("color", tausta);
Example: http://jsfiddle.net/HbAHS/8/
You can hide the element with CSS
.piiloteksti{display:none;} Fiddle
OR if you think that would interfere with your layout then,
.piiloteksti{visibility:hidden;} Fiddle
Or you can just give transparent color to your piiloteksti elements
.piiloteksti{color:transparent;} Fiddle

How to change two or more Div Styles in Javascript

Is there a way to change two or more Div styles with a single javascript line?
document.getElementById("searchScroll").style.position="fixed";
document.getElementById("searchScroll").style.margin="-50px";
Is it possible to merge the code in ONE line?
You can update it using a single line of JavaScript - but i would suggest leaving it as multiple - its easier to read and understand with multiple lines and you dont have to worry about replacing other style values.
You can go up a level and set the style, for example :
document.getElementById("searchScroll").style.cssText = "position:fixed;margin:-50px;";
this will replace the current style .. to add you can use the following :
document.getElementById("searchScroll").style.cssText += "position:fixed;margin:-50px;";
Example : http://jsfiddle.net/aDMke/
you can use cssText property.
document.getElementById("searchScroll").style.cssText = "position:fixed;margin:-50px"
but i will replace all other inline styles.
Alternatively, using jQuery:
$('#searchScroll').css({
'position': 'fixed',
'margin': '-50px'
});
You can use with (but Crockford won’t like it):
with(document.getElementById("searchScroll").style){position='fixed';margin='-50px';}
Or add on the cssText property (this is probably what you want):
document.getElementById("searchScroll").style.cssText += 'position:fixed;margin;-50px';
Demo: http://jsfiddle.net/V6gCC/

How to check if a css rule exists

I need to check if a CSS rule exists because I want to issue some warnings if a CSS file is not included.
What is the best way of doing this?
I could filter through window.document.styleSheets.cssRules, but I'm not sure how cross-browser this is (plus I notice on Stack Overflow that object is null for styleSheet[0]).
I would also like to keep dependencies to a minimum.
Is there a straightforward way to do this? Do I just have to create matching elements and test the effects?
Edit: If not, what are the cross-browser concerns of checking window.document.styleSheets?
I don't know if this is an option for you, but if it's a single file you want to check, then you can write your error message and toggle the style to hide it in that file.
<span class="include_error">Error: CSS was not included!</span>
CSS file:
.include_error {
display: none;
visibility: hidden;
}
I test for proper CSS installation using javascript.
I have a CSS rule in my stylesheet that sets a particular id to position: absolute.
#testObject {position: absolute;}
I then programmatically create a temporary div with visibility: hidden with that ID and get the computed style position. If it's not absolute, then the desired CSS is not installed.
If you can't put your own rule in the style sheet, then you can identify one or more rules that you think are representative of the stylesheet and not likely to change and design a temporary object that should get those rules and test for their existence that way.
Or, lastly, you could try to enumerate all the external style sheets and look for a particular filename that is included.
The point here is that if you want to see if an external style sheet is included, you have to pick something about that style sheet that you can look for (filename or some rule in it or some effect it causes).
Here is what I got that works. It's similar to the answers by #Smamatti and #jfriend00 but more fleshed out. I really wish there was a way to test for rules directly but oh well.
CSS:
.my-css-loaded-marker {
z-index: -98256; /*just a random number*/
}
JS:
$(function () { //Must run on jq ready or $('body') might not exist
var dummyElement = $('<p>')
.hide().css({height: 0, width: 0})
.addClass("my-css-loaded-marker")
.appendTo("body"); //Works without this on firefox for some reason
if (dummyElement.css("z-index") != -98256 && console && console.error) {
console.error("Could not find my-app.css styles. Application requires my-app.css to be loaded in order to function properly");
}
dummyElement.remove();
});
I would use a css selector like this from within your jquery widget.
$('link[href$="my-app.css"]')
If you get a result back it means there is a link element that has a href ending with "my-app.css"
Next use this function to validate a specific css property on an element you are depending on. I would suggest something specific to you styles like the width of a container rather something random like -9999 zindex
var getStyle = function(el, styleProp) {
var x = !!el.nodeType ? el : document.getElementById(el);
if (x.currentStyle)
var y = x.currentStyle[styleProp];
else if (window.getComputedStyle)
var y = document.defaultView.getComputedStyle(x, null).getPropertyValue(styleProp);
return y;
}
Like this
getStyle($('#stats-container')[0], "width")
or
getStyle("stats-container", "width")
If you are worried about not being able to edit other people's stylesheets, you can proxy them through a stylesheet of your own, using import
#import url('http://his-stylesheet.css');
.hideErrorMessage{ ... }
This is enough if you just want to know if your code is trying to load the stylesheet but won't help if you need to know if the foreign stylesheet was then loaded correctly.

Can someone REMIND me how to ADD to a .css value using jQuery

I feel silly asking this because I should know it but I'm in a hurry and I also can't for the life of my think of the right term to put into Google to get the answer I'm looking for.
Basically using javascript/jquery I need to say "add varName's value to the existing css property of left:200px;" using the the .css in jQuery.
Go through this
http://api.jquery.com/css/
//This will set or overwrite the left style property of element
//selected by elementSelector
$("elementSelector").css("left", varName);
Alternatively css method takes a map if you want to set multiple properties at once.
$("elementSelector").css( { left: varName });
Are you trying to increment the current CSS value with the one in your variable?
If so, use this:
var varName = 20;
$('#element').css('left', '+=' + varName);
$('.selector').css('opacity', '0.5');
or, for multiples:
$('.selector').css({'opacity' : '0.5', 'width' : '100px'});
or, for a specific class:
$('.selector').addClass('className');
http://api.jquery.com/css/
http://api.jquery.com/addClass/
var extra;
//fiddle with the value of extra
$("#myElement").css("left", 100 + extra +"px");

Categories

Resources