How to change two or more Div Styles in Javascript - 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/

Related

How to run a for loop inside a jQuery selector?

I am programming a WebExtension for Facebook which will invoke CSS based on their privacy settings.
$(document).ready(function(){
$("a[data-tooltip-content*='Public']").closest(".userContentWrapper._5pcr").css({"background-color": "yellow"});
$("a[data-tooltip-content*='Only Me']").closest(".userContentWrapper._5pcr").css({"background-color": "lime"});
$("a[data-tooltip-content*='friends']").closest(".userContentWrapper._5pcr").css({"background-color": "cyan"});
$("a[data-tooltip-content*='Public']").closest("._2tdc").css({"background-color": "yellow"});
$("a[data-tooltip-content*='Only Me']").closest("._2tdc").css({"background-color": "lime"});
$("a[data-tooltip-content*='friends']").closest("._2tdc").css({"background-color": "cyan"});
However, I noticed that a different page layout are has a different class value that I need to invoke with CSS codes.
Is there any way to write a for loop inside a jQuery selector?
$("a[data-tooltip-content*='Public']").closest("**For(a list of class name), loop through all of them)**").css({"background-color": "yellow"});
I have tried using $.each jQuery, but I really don't have much of an idea after reading through the documents.
var obj = {".userContentWrapper._5pcr" , "._2dc"};
$.each(obj, function(index,element)){
$("a[data-tooltip-content]").closest(obj).css({"background-color": "violet"});
$("a[data-tooltip-content*='Public']").closest(obj).css({"background-color": "yellow"});
$("a[data-tooltip-content*='Only Me']").closest(obj).css({"background-color": "lime"});
$("a[data-tooltip-content*='friends']").closest(obj).css({"background-color": "cyan"});
}
Sample result (original image link):
This should be as easy as storing all the class names in an array, and using a loop
var classses = ['.class1','.class2'];
for(var i=0;i<classes.length;i++)
$("a[data-tooltip-content*='Public']").closest(classes[i]).css({"background-color": "yellow"});
However, in general, multiple selectors can be separated with commas so this may also work.
$("a[data-tooltip-content*='Public']").closest('.class1, .class2')
.css({"background-color": "yellow"});
You almost did it yourself
$("a[data-tooltip-content*='Public']").closest(".class1, .class2, .class3").css({"background-color": "yellow"});

Jquery change background size AND image src

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.

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 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