JS newbie here
I want to have a kind of profile preview page where people can select a color (could be clicking on an image or could be a radio button) and that changes the background colors in certain divs in the preview page.
IE someone clicks on the button for red then the gradients in the background of the title bar, info boxes etc will turn to reds.
Whats the best way to do this?
I think you'd be best off if you define specific stylesheets for each 'color' (read: style) you want to be available to the user. If the user clicks on something to make his color choice, you can change the stylesheet that is loaded. You probably will need a default.css or a main.css file that contains all positioning and default coloring stuff and for each color you have a separate css file like red.css that will load the colors for each element in your dom you want to be changed.
In simple Javascript this could look something like:
<link rel="stylesheet" href="style1.css" id="stylesheet">
<script type="text/javascript">
function changeStyle() {
document.getElementById('stylesheet').href = 'style2.css';
}
</script>
Of course, you can also include a library like jQuery to do this for you. Another option (non JS) is to do a POST when the user picks a color and change the stylesheet server side. But that will make the page refresh.
Use jQuery:
$(document).ready(function(){
$('#my-button').click(function(){
$('.title-bar').css({'background' : 'red'});
});
});
Edit:
I just hacked together a better (as in "programmatic") solution: http://jsfiddle.net/eNLs6/
$(document).ready(function(){
$('.colorchanger').click(function(){
$('#preview-div').css({'background' : $(this).val()});
});
});
I think the best way to achieve that is to have different div classes for each color (theme in general) and change the css class of the div when button or image clicked :
$('#myRedButton').click(function(){$('#myDiv').attr('class','red')});
$('#myBlueButton').click(function(){$('#myDiv').attr('class','blue')});
And you will have a html looking like
<div id="myDiv">....the div that will have it's color changed </div>
<img src="..." id="myRedButton"/>
<img src="..." id="myBlueButton"/>
Create a base stylesheet (base.css) for general stuff and then secondary ones for each colour, eg red.css, blue.css
When a users clicks the red image, it loads the red.css stylesheet.
$('#red').click(function() {
//load red.css
}
See this question on how to change a secondary stylesheet with jQuery for more details.
I would add a class to the body and then use that in the stylesheet to create different themes.
JS:
$('#red').click(function() {
document.body.className = 'red';
});
CSS:
body.red .title{background:url('red-gradient.png');}
body.red .color{color: red}
/* etc... */
You can of course put each theme in a separate CSS file, to make things easier to organize. But for performance reasons, I suggest you load all CSS at once and just swap classes onclick, instead of a dynamic stylesheet loader .
Related
How do I make the color of a section change in a HTML menu made of DIVs when that section is selected?
Basically, I am creating a menu such as the one on the left of this image:
http://docs.shopify.com/assets/images/manual/orders/orders.jpg?1386029140
How do I make the corresponding section we are on to be "illuminated"?
Do I do it with PHP and having a variable for each div's class?
This probably wouldn't be done with PHP, as PHP is server side, JavaScript is more what your looking for as it runs on the clients machine and can be used to respond to clients actions such as mouse clicks.
You can do this with some CSS and Jquery.
First include your Jquery library in your HTML, place this <script src="jquery-1.10.2.min.js"></script> in the <head> tags
Then you can use
$( "#target" ).click(function() {
$(this).css.backgroundColor = "red";
});
Where #target is the name of the DIV Id or Class you want to select.
The reason I need to do this is that the website I'm working on uses the exact same template to display dynamic content for multiple pages. All pages replicate the exact same div id's because they display the content the same way (except for the header content!). The header content shortens however the div id's still remain within the source code.
The blog index page needs to display 1 background image while every other page on the website displays another background image.
Thanks in advance for any help.
This snippet of code will do what you want:
if (window.location.href.indexOf('somepart_of_the_url') != -1) {
//Change background to some div
$('#somediv').css('backgroundImage','url(images/mybackgroundimage.jpg)');
//Change background to page body
$("document.body").css('backgroundImage','url(images/mybackgroundimage.jpg)');
}
I often give the body class a name based on the template or request path. I know you said that they all use the same template, but that template takes params and one of the params should be
body_class
And whatever controller/dynamic thing you have populating your site and rendering the template, should pass in 'home' when you're at /. In my previous experience, I would pass in other things as well so that /blog/category/post might have a body class like
<body class="post two-column-a">
Then your selectors are something like:
body { ... }
body.home { ... }
This works:
<script language="javascript">
$(document).ready(function() {
if (window.location.href.indexOf('INDEX_URL') != -1) {
//Change background
$('#DIV_ID').css({'background-image': 'url(http://URL.com/images/BG.jpg)', 'background-repeat': 'repeat-x', 'background-position': 'center top', 'width': '100%!important', 'min-height': '400px'});
}
});
</script>
The flaw that this code has though is that if you insert a directory into "INDEX_URL" such as /folder/, any page after /folder/ will have that background.
I'm currently working on my own Wordpress theme. I thought it'd be cool to have a dropdown box in the sidebar in which you can choose different themes, and it'll change the page background, border colors, etc a bit.
The thing is, for one theme (the default one) I have Javascript in my header.php file where the header image will change each refresh. I want this header image to go away when switching stylesheets, but it just overlaps the other one. How do I change this?
If you want to see for yourself, the box is in the right sidebar under the blue buttons. This is my testing website. Ignore the 000webhost stuff.
http://trainman1405.site11.com/wordpress/
Thank you!
The general solution here is to define all of your styles in one sheet, but namespace them so you can simply change the class on the body and the new styles will take effect. (You could also define them in separate sheets, using the namespaces, and simply reference every sheet in your <head>.)
For example, some CSS:
body a { color: #00f; } /* default */
body.green a { color: #090; }
body.red a { color: #f00; }
And then when you want to change it (using jQuery, although plain Javascript could do this job too):
$('#theme_select').change(function()
{
$('body').removeClass('green').removeClass('red'); // remove existing classes
$('body').addClass($(this).val());
});
it looks like you could use a javascript library its called jquery. You could use that to hide and display a new image e.g
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.js"></script>
<script type="text/javascript">
function piczotheme() {
$("defualttheme").hide()
$("mountaintheme").hide()
//and then show load add your picture
$('#defualt').css("background-image", "url(url of the picture)");
}
</script>
and then you have to set up a button or something to trigger this effect
so...
<button onclick="piczotheme()"> click </button>
I am building a website that displays recipes. Each recipe appears as part of a blog entry, and will have a link at the bottom to Print this recipe.
What I want to happen is a click on the link opens a new window and fills it with a print-friendly-styled version of the recipe, which is already inside its own <div class="recipe">.
Can I do this with JS/jQuery alone, or do I need to process from the server side? Any ideas how to do this?
EDIT: What would be ideal would be to generate a PDF on the fly, but in lieu of that I'd like a new window, containing only the recipe, for the visitor to print out or save, as they see fit. Print-styles are nice, but most people don't know they exist and can't be bothered to check and see by printing out a page that doesn't look print ready.
There is no need to load a different stylesheet and the only javascript you will need is for triggering the printing dialog.
With CSS alone you can add rules that are only used when printing, you can either use media queries
<style type="text/css">
#media print{
//css printing rules
}
</style>
or use the link tag:
<link rel="stylesheet" media="print" href="styles.css" type="text/css" />
UPDATE: If you want to update the stylesheet on the fly without openning a new window i suggest you check out this Nettuts article or a simpler solution:
$("#css-switch").click(function() {
$("link[rel=stylesheet]").attr({href : "red.css"});
});
You can do this simply with CSS alone if you have it load the exact same page but with a different stylesheet.
Yes, you can(Hello Mr. Obama).
Most browsers allow you to pass in a data: format string, like
window.open('data:text/html;charset=utf-8,text%20to%20show');
which would open a new window / tab (that is browser config dependend) with the Content "text to show". You can pass in HTML code in the same manner, probably escaped.
var print = $('<div>', {
id: 'foobar',
html: 'Hello world',
css: {
backgroundColor: '#ff0000',
color: '#ffffff',
width: '200px',
height: '200px'
}
}),
opener = $('<div>').append(print);
window.open('data:text/html;charset=utf-8,' + opener.html());
Demo: http://www.jsfiddle.net/4yUqL/73/
You'll probably need to do a request to the server on the print page and fill in the form fields with the data.
If i was you, i'd go for the pdf creating solution. It is fairly simple to create pdf's on the fly in php, and it will almost certainly give a better user experience to your main audience.
If you want to skip that excersise, i'd do it the following way:
1: fetch the data you need as JSON on the original non-printerfriendly page, and use clientside templating to build the ui. Store the JSON for use on the printerfriendly page
2: when you open the new window, use the exact same method, but use another template optimized for printing.
I build a css file using PHP which allows me to easily customize the color of many elements. Is it possible for me to "rebuild" the stylesheet and apply it to the page in the DOM using Jquery?
eg.
<?php
if (isset($_POST['mycolor'])){
$myColor = $_POST['mycolor'];
} else {
$myColor = "blue";
}
?>
<style type='text/css'>
.style1{
color:<?php $myColor;?>;
}
</style>
Now on my page I have a link you can click called "change color to red" and when you click "red" it does a $.post to my php script, which rebuilds the css including .style1 - and allows the page to change the stylesheet.
I haven't tested this but would it even work? If I echo'ed out the new stylesheet after the post into the dom... would it even apply to the page?
You can do something like this if your whole stylesheet is php generated:
function newCSS(params){
$("link[href*=myStyles.php]:last").after('<link href="myStyles.php?'+ params +'" type="text/css" rel="Stylesheet" />');
$("link[href*=myStyles.php]:first").remove();
}
This replaces the link in the head with the new one...the new styles will take effect once it's loaded.
You could use the css function to set different css properties on elements:
$('.style1').css('color', 'red');
I recommend you to create your dynamic css as a php-file. More info here: http://www.barelyfitz.com/projects/csscolor/
EDIT:
Here's an improved solution using selector provided by Nick:
$("link[href*=myStyles.php]").attr('href','myStyles.php');
I don't know if you've ever heard about LESS. It's a nice little tool that makes it possible for you to have "variables" in your CSS. Which seems to be what you are really wanting.
Have a look at This blog post which should help you.