For example, I have this CSS script:
<style>
.header{
background:none:
color:#fff;
}
</style>
Then, I would like to change the header value to:
<style>
.header{
background-color:#fff:
color:#000;
}
</style>
The values are stored in database. What makes me confused is which should be the best to do that: Using PHP script or CSS or even javascript.
I want it changed based on the CSS value from my database which I can change again when I need it (by using PHP script). Perhaps this question is too general but, please give me some scripts which I can perform it well.
Thanks for any help.
first, change the extension of your file from (e.g.) style.css to style.php . Then add this to the first line of your css:
<?php
header('Content-Type: text/css');
?>
and after that you can define the value of your background as a variable and change it easily.
background: <?php echo $value; ?>
and in your php file:
<?php value = "#fff"; ?>
UPDATE:
<?php $value = "#fff"; ?>
For maintainability and flexibility reasons, I want to propose the frontend, not a backend solution (also because so far nobody proposed that).
I especially like the approach taken in the Grips library, where you can compile CSS template, passing in variables as an input (i.e. colors), and get the CSS to use. All of that can happen in the browser. And you can use Grips for HTML templating as well.
As I mentioned in the comment, this video is the best introduction to Grips.
Also note that if you want to use Grips in the backend, you can - but it's a JS library, so it wouldn't fit perfectly into your PHP solution.
I think its same for both way.
If you want to use php then you will have to use inline css or style tag and its simple to.
Like
$color = (!dbValue?"defaule value":dbValue);
<style>
.header{
background-color:<?=$color?>:
color:#000;
}
</style>
Make a php page in that write
$row = mysql_fetch_array(mysql_query('select * from table'));
<style>
.header{
background-color: <?php echo $row['bg_color_from_db']; ?> //change variable
color:<?php echo $row['color_from_db']; ?>; //change variable
}
</style>
In order to achieve this you will need to use all three together, I am assuming you are using a LAMP set up on the back end. You will use PHP to first retrieve the values and store them, here is a good post to show this.
Link to Example on Stackoverflow
Once you have your values stored you will then need to create a file to change the DOM using JavaScript. Here is a good starting point produced by Mozilla Developers:
Mozilla JavaScript and CSS
The reason I suggest using JavaScript to achieve this is the ability to listen for events and change the client side in response. Hope this helps.
Import your database here In css or include db page;
$bg_color=$_row['column name'];
background-color:$bg_color;
And something like this you will be able to change your Background color using the value stored in database
Related
Is it possible to use Javascript inside CSS?
If it is, can you give a simple example?
IE and Firefox both contain ways to execute JavaScript from CSS. As Paolo mentions, one way in IE is the expression technique, but there's also the more obscure HTC behavior, in which a seperate XML that contains your script is loaded via CSS. A similar technique for Firefox exists, using XBL. These techniques don't exectue JavaScript from CSS directly, but the effect is the same.
HTC with IE
Use a CSS rule like so:
body {
behavior:url(script.htc);
}
and within that script.htc file have something like:
<PUBLIC:COMPONENT TAGNAME="xss">
<PUBLIC:ATTACH EVENT="ondocumentready" ONEVENT="main()" LITERALCONTENT="false"/>
</PUBLIC:COMPONENT>
<SCRIPT>
function main()
{
alert("HTC script executed.");
}
</SCRIPT>
The HTC file executes the main() function on the event ondocumentready (referring to the HTC document's readiness.)
XBL with Firefox
Firefox supports a similar XML-script-executing hack, using XBL.
Use a CSS rule like so:
body {
-moz-binding: url(script.xml#mycode);
}
and within your script.xml:
<?xml version="1.0"?>
<bindings xmlns="http://www.mozilla.org/xbl" xmlns:html="http://www.w3.org/1999/xhtml">
<binding id="mycode">
<implementation>
<constructor>
alert("XBL script executed.");
</constructor>
</implementation>
</binding>
</bindings>
All of the code within the constructor tag will be executed (a good idea to wrap code in a CDATA section.)
In both techniques, the code doesn't execute unless the CSS selector matches an element within the document. By using something like body, it will execute immediately on page load.
I think what you may be thinking of is expressions or "dynamic properties", which are only supported by IE and let you set a property to the result of a javascript expression. Example:
width:expression(document.body.clientWidth > 800? "800px": "auto" );
This code makes IE emulate the max-width property it doesn't support.
All things considered, however, avoid using these. They are a bad, bad thing.
To facilitate potentially solving your problem given the information you've provided, I'm going to assume you're seeking dynamic CSS. If this is the case, you can use a server-side scripting language to do so. For example (and I absolutely love doing things like this):
styles.css.php:
body
{
margin: 0px;
font-family: Verdana;
background-color: #cccccc;
background-image: url('<?php
echo 'images/flag_bg/' . $user_country . '.png';
?>');
}
This would set the background image to whatever was stored in the $user_country variable. This is only one example of dynamic CSS; there are virtually limitless possibilities when combining CSS and server-side code. Another case would be doing something like allowing the user to create a custom theme, storing it in a database, and then using PHP to set various properties, like so:
user_theme.css.php:
body
{
background-color: <?php echo $user_theme['BG_COLOR']; ?>;
color: <?php echo $user_theme['COLOR']; ?>;
font-family: <?php echo $user_theme['FONT']; ?>;
}
#panel
{
font-size: <?php echo $user_theme['FONT_SIZE']; ?>;
background-image: <?php echo $user_theme['PANEL_BG']; ?>;
}
Once again, though, this is merely an off-the-top-of-the-head example; harnessing the power of dynamic CSS via server-side scripting can lead to some pretty incredible stuff.
Not in any conventional sense of the phrase "inside CSS."
IE supports CSS expressions:
width:expression(document.body.clientWidth > 955 ? "955px": "100%" );
but they are not standard and are not portable across browsers. Avoid them if possible. They are deprecated since IE8.
I ran into a similar problem and have developed two standalone tools to accomplish this:
CjsSS.js is a Vanilla Javascript tool (so no external dependencies) that supports back to IE6.
ngCss is an Angular Module+Filter+Factory (aka: plugin) that supports Angular 1.2+ (so back to IE8)
Both of these tool sets allow you to do this in a STYLE tag or within an external *.css file:
/*<script src='some.js'></script>
<script>
var mainColor = "#cccccc";
</script>*/
BODY {
color: /*{{mainColor}}*/;
}
And this in your on-page style attributes:
<div style="color: {{mainColor}}" cjsss="#sourceCSS">blah</div>
or
<div style="color: {{mainColor}}" ng-css="sourceCSS">blah</div>
NOTE: In ngCss, you could also do $scope.mainColor in place of var mainColor
By default, the Javascript is executed in a sandboxed IFRAME, but since you author your own CSS and host it on your own server (just like your *.js files) then XSS isn't an issue. But the sandbox provides that much more security and peace of mind.
CjsSS.js and ngCss fall somewhere in-between the other tools around to accomplish similar tasks:
LESS, SASS and Stylus are all Preprocessors only and require you to learn a new language and mangle your CSS. Basically they extended CSS with new language features. All are also limited to plugins developed for each platform while CjsSS.js and ngCss both allow you to include any Javascript library via <script src='blah.js'></script> straight in your CSS!
AbsurdJS saw the same problems and went the exact opposite direction of the Preprocessors above; rather than extending CSS, AbsurdJS created a Javascript library to generate CSS.
CjsSS.js and ngCss took the middle ground; you already know CSS, you already know Javascript, so just let them work together in a simple, intuitive way.
This turns out to be a very interesting question. With over a hundred properties being set, you'd think that you'd be allowed to type
.clickable { onclick : "alert('hi!');" ; }
in your CSS, and it'd work. It's intuitive, it makes so much sense. This would be amazingly useful in monkey-patching dynamically-generated massive UIs.
The problem:
The CSS police, in their infinite wisdom, have drawn a Chinese wall between presentation and behavior. Any HTML properly labeled on-whatever is intentionally not supported by CSS. (Full Properties Table)
The best way around this is to use jQuery, which sets up an interpreted engine in the background to execute what you were trying to do with the CSS anyway. See this page:
Add Javascript Onclick To .css File.
Good luck.
I have a "catalog" which is basically a (Divi) image gallery, where the prices are hidden for not-logged on users. The price is the image caption which is hidden on every page with CSS. However (of course) the element (price) is still in the source code which is not the intention, because it may only be seen by logged in clients.
The caption is hidden with this code:
.et_pb_gallery_caption {visibility:hidden;}
I've tried to add this javascript to completely remove the element from the source code:
if ( $(element).css('visibility') == 'hidden' ){
$(element).remove();
}
But that doesn't do the trick. Hopefully someone can help me.
Thanks in advance!
<?php if($userLoggedIn){ ?>
<caption>$9.99</caption>
<?php } ?>
as a commentor mentioned, you need to do this server side so the HTML sent over to the browser does not include your price.
Please note - i made up the name for the logged in check, you need to search for the proper variable in your wordpress install that represents different user log in and their types.
It is an ambiguous question without having source code snippet, btw if you are trying to remove the element whose visibility is set to hidden you can use following jquery code to remove it from the DOM as:
$(document).ready(function(){
$(".et_pb_gallery_caption").remove();
});
However, one can better comment if you show some code snippet.
I have a bunch of small tables that are formatted as inline-block elements. In the browser they display side by side as intended, but when using mPDF to output them they break after each table. No matter how I try to format them, they always break after the table. Is there a trick with mPDF to get elements to stack side-by-side?
I am pulling the exact HTML from the page and sending it via AJAX
Below is an example of the browser and pdf view.
My mPDF generator page looks like this:
<?php
include("mpdf60/mpdf.php");
$html = $_POST['html'];
$mpdf=new mPDF('utf-8', 'A4');
$mpdf->SetDisplayMode('fullpage');
// LOAD a stylesheet
$stylesheet = file_get_contents('../../_css/main.css');
$mpdf->WriteHTML($stylesheet,1); // The parameter 1 tells that this is css/style only and no body/html/text
$mpdf->WriteHTML($html);
$mpdf->Output('myPDF.pdf','D');
exit;
?>
I try a lot of thinks too, but finally i found a solution, just use:
float: left;
Thats work for me.
I've spent a couple of hours figuring out how to make inline <div> or <p> elements with mPDF. I found some limitations, which contains the inline-block too. The display: inline or display: inline-block is ignored. You have to put everything in <span> elements if you want to see them one beside the other.
I want to truncate a given string taken from MySQL database through PHP to fit within given pixels. Most of the solutions I found were based on number of characters. But I specifically want it according to pixel length.(I don't want to use monospace font)
I found out that $('#idName').width() can be used in JavaScript for fitting. And that works fine with strings written in HTML simply. But here is the deal. My string is a variable stored in PHP, I need JavaScript to get width in pixels and I need to have that string in a span (in HTML) with specific id name.
So, I have tried to make it work using all three of them- PHP, HTML and JavaScript. Below is my code.
<?php
$len=100;
?>
<span id='d' style="display:none;"><?php echo substr($details,0,$len) ?></span>
<script>
var len=370;
while($('#d').width()>len){
<?php
$len=$len-1;
echo "<span id='d' style='display:none;'>" . substr($details,0,$len) . "</span>";
?>
}
<?php echo substr($details,0,$len); ?>
</script>
So I take my string's first 100 letters and put them in a span with id d. Then in JavaScript, I get its width and check in while loop. I run while loop (keep decreasing $len) until the pixel length of the substring is within desired width and keep redifining that substring in span with same id. Then I print that substring.
Could someone please change the code to make it work or suggest a better method? I am newbie in this, so please make it as simple as you can.
As far as I understand from your question, you are trying to hide an overflow when the string is longer than container given?
I would rather suggest using overflow:hidden; white-space:nowrap; and maybe some text-overflow:ellipsis; to make "..." effect just before the end of container. But you have to remember, that fonts render differently through most browsers and operating systems, so the user experience might be different on Windows than on Mac.
That probably won't work. JS and PHP can't be mixed like that. The while loop is useless.
One solution that came to my mind is that you can first get the PHP string, through ajax, and then display it according to the width using JS.
I'm having a hard time figuring out what is the best way to transfer information from PHP to Jquery. I know putting PHP in Javascript is a really bad alternative (my JS and PHP files are seperated anyway), so what I usually do is print the info with PHP in the HTML with a input type hidden and retrieve the info in JQuery using the element.text() or .val() or any other method, but I feel this is kind of noobish. Is there a better way?
I recommend never using a server-side language to build JavaScript. Instead, keep your data in HTML (model), your styles in CSS (view), and your interactions in JS (controller).
When you need to pass data to JavaScript, make good use of attributes and templates.
When it comes to passing data via attributes, you can go a long way with just using native attributes.
In this example, it is quite apparent that the link will open a modal, and the [href] attribute is used to point to where the modal lives:
Open modal
<div id="modal">lorem ipsum</div>
When you can't fit data within native attributes, you should make use of [data-*] attributes.
In this example, [data-tooltip] is being used to store a rich-text tooltip.
<div data-tooltip="<p>lorem ipsum</p>">...</div>
Even more importantly, jQuery automatically grabs and casts all [data-*] attributes on a DOM node when .data() is called on the node.
<div id="example"
data-foo="bar"
data-fizz="true"
data-max="100"
data-options="{"lorem":"ipsum"}">
...
</div>
<script>
$('#example').data();
/*
{
foo: 'bar',
fizz: true,
max: 100
options: {
lorem: 'ipsum'
}
*/
</script>
The thing to watch out for is JSON encoding within HTML encoding. jQuery makes it very straight-forward to get the data out of the DOM node without needing to worry about decoding, but in PHP you need to make sure that you json_encode data before calling htmlentities:
<div data-example="<?= htmlentities(json_encode($someArray)) ?>">...</div>
In some instances you may want to make use of jQuery's .attr() method.
For large amounts of data, such as an HTML template string, you can use <script> tags with a template mime type (such as type="text/x-jquery-tmpl"):
<script id="template-example" type="text/x-jquery-tmpl">
<h1>${title}</h1>
<p>${body}</p>
</script>
Or you can use the HTML5 <template> element:
<template id="template-example">
<h1>${title}</h1>
<p>${body}</p>
</template>
You can then access the HTML contents of the element run it through whatever your favorite flavor of string templating happens to be.
You can simply echo PHP variables into Javascript variables for your jQuery to use like this:
<?php
$stringVar = "hi";
$numVar = 1.5;
?>
<script>
var stringVar = "<?php echo $stringVar; ?>";
var numVar = <?php echo $numVar; ?>;
</script>
This can be used for practically any data type as long as you convert it correctly upon echoing it (oftentimes json_encode() is enough for complex structures such as arrays and objects).
Also note that this way will only work if your jQuery code is included after these variables have been defined.
The other way is to look into using AJAX, but if these are static variables that don't need to change within the lifetime of the page then I would go with the method above.