If Div is empty, hide it and change width of another div - javascript

I am new to css and php and am trying to find a way to hide my .item-page aside if the Div is empty. And then change the width of item-page to 100%. Right now the aside takes up 85px empty or not. How can do this in my php file?
Here is my CSS:
item-page {
position:relative;
width: 100%;
}
.item-page aside {
float:left;
position:absolute;
width:85px;
}
gk-article {
font-size:14px;
line-height:26px !important;
margin:0 0 80px 110px;
}
Here is my php file:
<div id="main">
<jdoc:include type="component" />
</div>

You've tagged javascript/jquery here, and that's probably what you should use (not PHP).
(in jQuery) you can do something like this - use classes as charlietfl suggested:
if( $('.item-page aside').html() == '') ) {
$('.item-page aside').hide();
$('.item-page').removeClass('isntempty').addClass('isempty');
} else {
$('.item-page aside').show();
$('.item-page').removeClass('isempty').addClass('isntempty');
}
CSS:
.isntempty {
width: 100%;
}
.isempty {
width: 50%; /* whatever your default width is */
}

You could set up different css class rules for empty vs not empty. These rules would set widths and/or display. Empty element would be zero...or don't even print it. Then run whatever test in your server code that determines status...and apply appropriate calsses to the elements

check by js in php:
<?php
...
echo "<script>if (document.getElementById('divId').innerText=='')
//or document.getElementById('divId').textContent=='' in firefox//
$('#divId').attr('style','width:100%;');
</script>";
...
?>

You can use Javascript, with the jQuery framework you could do this :
<script type="text/javascript">
$( document ).ready(function() {
//Hide if empty
if( $('.item-page').is(':empty') ) {
$('.item-page').hide();
}
//Change to width 100%
$('.item-page').css({width:'100%'});
});
</script>
Learn more here :
http://api.jquery.com/empty-selector/
http://learn.jquery.com/using-jquery-core/document-ready/

Related

Using Javascript/Php: Trying to display background image - logic wrong?

So I want to display a background image (that is the thumbnail image in wordpress post) using css in hero-wrapper div if the screen size is min. 900px.
I have using php to check if there is a thumbnail image, then using javascript to check screen width and then adding background-image property to the dive. Not working, I think my logic is wrong??
HTML
<?php
if ( has_post_thumbnail() ) { ?>
<?php $thumb = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), 'full' );?>
<script type="text/javascript">
if (jQuery(window).width() == 900) {
<?php echo '<section class="hero-wrapper" style="background-image: url(' . $thumb['0']. ') >'; ?>
}
</script>
<?php } ?>
<section class="hero-wrapper">
<figure class="frontpage-hero">
<div class="banner-box">
<h2>GET YOUR FREE CASE ASSESSMENT?</h2>
<h6>Enter your details below for a consultation</h6>
<form>
<input type="text" name="name" placeholder="Name..">
<input type="text" name="email" placeholder="Email..">
<input type="submit" name="submit">
</form>
</div>
</figure>
</section>
css
.hero-wrapper {
margin: 0;
padding: 0;
min-height: 669px;
background-repeat: no-repeat;
}
#media screen (min-width: 900px) {
.hero-wrapper {
min-height: 669px;
background-repeat: no-repeat;
}
}
You are echoing a <section> tag inside a <script> tag.
You should change this
<script type="text/javascript">
if (jQuery(window).width() == 900) {
<?php echo '<section class="hero-wrapper" style="background-image: url(' . $thumb['0']. ') >'; ?>
}
</script>
To something like this
<script type="text/javascript">
if (jQuery(window).width() >= 900) {
$('.hero-wrapper').css('background-image', 'url(' + <?php echo $thumb['0']; ?> + ')');
}
</script>
Your assumption is wrong twice:
your jQuery(window).width() == 900 condition will run only once and will not reflect window size changes
you're trying to use php (server side language) to output html (client side markup) inside javascript (client side code) code block. You will end up with syntax error.
Correct approach is to just output your html element and use CSS media queries to control its appearance. Something like:
.hero-wrapper {
display: none;
}
#media (min-width: 900px) {
.hero-wrapper {
display: block;
}
}
Please also notice that image displayed as background will not enforce element to have any height and hence your element will show up with 0px height (invisible in other words). You will need to specify element's dimensions somehow (and remember that images may have different aspect ratios).
After all it may be easier for you to not use background image but insert normal image instead and control its dimensions using CSS.
You're not adding anything to the existing "hero-wrapper" div with your code, you're just echoing some HTML within a Javascript block, which won't achieve anything. You've almost certainly got syntax errors in your console. The final rendered page will look something like this:
<script type="text/javascript">
if (jQuery(window).width() == 900) {
<section class="hero-wrapper" style="background-image: url('thumbnail.png') >
}
</script>
<section class="hero-wrapper">
<figure class="frontpage-hero">
...etc
This will get you a JS console error along the lines of:
Uncaught SyntaxError: Unexpected token <
Even if that part worked, the HTML is also invalid because you never close the style attribute with a ", and this code will only ever execute when the window width is exactly 900px, which I don't think you intended.
What you need to be doing is altering the existing div to add the style, and also allow it when the width is greater than or equal to 900px. This should do it:
<script type="text/javascript">
$(document).ready(function() {
if ($(window).width() >= 900) {
$(".hero-wrapper").css("background-image", "url('<?php echo $thumb['0']; ?>')");
}
});
</script>
I also wrapped the code in document.ready so that it won't run until the page is ready.
I'd remove the javascript and do this in your CSS media queries with display: none; to hide the element for screens under 900px i.e
HTML/PHP
<?php
if ( has_post_thumbnail() ) {
$thumb = wp_get_attachment_image_src(
get_post_thumbnail_id($post->ID), 'full' );
echo '<section class="hero-wrapper" style="background-image: url(' . $thumb['0']. ') >';
} ?>
And in your CSS
#media screen (min-width: 900px) {
.hero-wrapper {
min-height: 669px;
background-repeat: no-repeat;
display: block;
}
}
#media screen (max-width: 900px) {
.hero-wrapper {
display: none;
}
}

Change CSS Property through JavaScript. (Uses ID's and Classes)

I'm trying to resize a panel using JavaScript to fit a small image into a panel, and struggling badly.
It's within the bold:
<body id="visCinemaTransRefund"><br>
<div id="content"><br>
<ul class="PayPanel" id="paymentDetails"><br>
Here's the CSS that needs modifying:
visCinemaTransRefund .PayPanel { width: 435px; }
How would I be able to modify with width of this panel?
I've also got a form I'm trying to resize within CSS:
visCinemaTransRefund FORM (width: 1005px;)
document.getElementById('paymentDetails').style.width = '1000px';
Have you tried using:
document.getElementById("paymentDetails").getElementsByClassName("PayPanel")[0].style.width="1000px"
Remember: getElementsByClassName return an array of elements, so using [0] you are indexing first element (and, of course, the only one).
Since getElementsById return a single elements, getElementsByClassName could be useless.
If you want to do this using CSS class :
HTML:
<div id="myDiv" class="medium"></div>
<button id="btn">Click me</button>
CSS:
#myDiv {
background-color: gray;
}
.medium {
height: 50px;
width: 50px;
}
.big {
height: 100px;
width: 100px;
}
JS:
document.getElementById("btn").onclick = function() {
var element = document.getElementById("myDiv"); // or document.getElementsByClassName("className")
if (element.className == "medium") {
document.getElementById("myDiv").className = "big";
} else {
document.getElementById("myDiv").className = "medium";
}
};
JSFIDDLE
Use the following code to change the width of tags by accessing HTML element from the DOM using getElement functions and setting width to it using setAttribute javaScript function.
document.getElementById("paymentDetails").setAttribute("style","width:500px;");
document.getElementById("visCinemaTransRefund").getElementsByTagName("form")[0].setAttribute("style","width:1000px;");
Using JavaScript:
document.getElementById('paymentDetails').style.width = '1000px';
Using JQuery:
$("paymentDetails").width(1000);
$("paymentDetails").css("width","1000px");

show loading icon until the page is load?

I wanted to show a loading icon to users until the page elements are fully loaded. How can I do that with javascript and I want to do it with javascript, not jquery?
Here is a link how google does it
How can I do this?
triggering some function on onload event or something like this .. I know it will be done somewhat like this or any other ways to do it?
Or there is some event for it?
UPDATE
I did something using display property I hide the body element but and onload of body tag I change its property but where to put the loading icon and add more interactivity.
HTML
<body>
<div id="load"></div>
<div id="contents">
jlkjjlkjlkjlkjlklk
</div>
</body>
JS
document.onreadystatechange = function () {
var state = document.readyState
if (state == 'interactive') {
document.getElementById('contents').style.visibility="hidden";
} else if (state == 'complete') {
setTimeout(function(){
document.getElementById('interactive');
document.getElementById('load').style.visibility="hidden";
document.getElementById('contents').style.visibility="visible";
},1000);
}
}
CSS
#load{
width:100%;
height:100%;
position:fixed;
z-index:9999;
background:url("/loading.gif") no-repeat center center rgba(0,0,0,0.25)
}
Note:
you wont see any loading gif if your page is loaded fast, so use this code on a page with high loading time, and i also recommend to put your js on the bottom of the page.
DEMO
http://jsfiddle.net/6AcAr/ - with timeout(only for demo)
http://jsfiddle.net/47PkH/ - no timeout(use this for actual page)
update
http://jsfiddle.net/d9ngT/
The easiest way to put the loader in the website.
HTML:
<div id="loading"></div>
CSS:
#loading {
position: fixed;
width: 100%;
height: 100vh;
background: #fff url('images/loader.gif') no-repeat center center;
z-index: 9999;
}
JQUERY:
<script>
jQuery(document).ready(function() {
jQuery('#loading').fadeOut(3000);
});
</script>
add class="loading" in the body tag then use below script with follwing css code
body {
-webkit-transition: background-color 1s;
transition: background-color 1s;
}
html, body { min-height: 100%; }
body.loading {
background: #333 url('http://code.jquery.com/mobile/1.3.1/images/ajax-loader.gif') no-repeat 50% 50%;
-webkit-transition: background-color 0;
transition: background-color 0;
opacity: 0;
-webkit-transition: opacity 0;
transition: opacity 0;
}
Use this code
var body = document.getElementsByTagName('body')[0];
var removeLoading = function() {
setTimeout(function() {
body.className = body.className.replace(/loading/, '');
}, 3000);
};
removeLoading();
Demo: https://jsfiddle.net/0qpuaeph/
HTML, CSS, JS are all good as given in above answers. However they won't stop user from clicking the loader and visiting page. And if page time is large, it looks broken and defeats the purpose.
So in CSS consider adding
pointer-events: none;
cursor: default;
Also, instead of using gif files, if you are using fontawesome which everybody uses now a days, consider using in your html
<i class="fa fa-spinner fa-spin">
Element making ajax call can call loading(targetElementId) method as below to put loading/icon in target div and it'll get over written by ajax results when ready. This works great for me.
<div style='display:none;'><div id="loading" class="divLoading"><p>Loading... <img src="loading_image.gif" /></p></div></div>
<script type="text/javascript">
function loading(id) {
jQuery("#" + id).html(jQuery("#loading").html());
jQuery("#" + id).show();
}
HTML page
<div id="overlay">
<img src="<?php echo base_url()?>assest/website/images/loading1.gif" alt="Loading" />
Loading...
</div>
Script
$(window).load(function(){
//PAGE IS FULLY LOADED
//FADE OUT YOUR OVERLAYING DIV
$('#overlay').fadeOut();
});
firstly, in your main page use a loading icon
then, delete your </body> and </HTML> from your main page and replace it by
<?php include('footer.php');?>
in the footer.php file type :
<?php
$iconPath="myIcon.ico" // myIcon is the final icon
echo '<script>changeIcon($iconPath)</script>'; // where changeIcon is a javascript function whiwh change your icon.
echo '</body>';
echo '</HTML>';
?>

How to pack contents in a div to move to the right when content reaches bottom of the div

Im generating some content with PHP, but after the number of contents is more than 5 the height becomes greater than that of the div, so i don't want it to stack on top of the div, but to move to the right of the div and start from the top. Here's an image.
PHP
echo '<a class="LibSectOpen">
<span style="display:none" class="SectionName">'.$Section.'</span>
<div class="LibrarySects"><div class="LibrarySectsHeader">'.$Section.'</div>
<div class="LibrarySectsShelf">';
while($row = mysql_fetch_array($log2)){
echo '<div class="LibrarySectsShelf_Book" style="background-color:'.$Color.'"
title="Author: '.$row['bbookauthor'].'">'.$row['bbookname'].'</div>';
}
echo ' </div>
</div>
</a>';
As it looks, the philosophy books in the example goes down, and i want it to go to the right and start another column of five books and so on.
Any ideas i can do this with JQuery and CSS?
.LibrarySectsHeader {
border:1px #CCC solid;width:500px; margin:2px; padding:1px; height:18px;border-radius:2px 2px 2px 2px; font-size:10px; color:rgba(0,0,0,1) !important; background-color: rgba(255,255,255,0.6); line-height:18px;
}
.LibrarySectsShelf {
border:1px #CCC solid;width:499px; margin:2px; padding:1px; height:129px;border-radius:2px 2px 2px 2px; font-size:10px; background-color: rgba(255,255,255,0.2); line-height:18px; background-image:url(images/bg/wood.jpg); background-size:100%; background-repeat:no-repeat;
}
.LibrarySectsShelf_Book {
border:1px #C90 solid;width:148px;height:23px; margin-bottom:1px;border-radius:3px 3px 3px 3px; font-size:10px; background-color: rgba(51,153,255,0.9); padding-left:2px; line-height:22px; color:rgba(255,255,255,1) !important; overflow: hidden;
}
.LibraryBooks {
border:1px #CCC solid;width:502px; margin:2px; padding:1px;border-radius:2px 2px 2px 2px; font-size:10px; background-color: rgba(102,102,102,1); line-height:18px;
}
You can achieve the output you want using only PHP,HTML,CSS solution which you are already using:
PHP
$i=1;
echo '<a class="LibSectOpen">
<span style="display:none" class="SectionName">'.$Section.'</span>
<div class="LibrarySects"><div class="LibrarySectsHeader">'.$Section.'</div>
<div class="LibrarySectsShelf"><div class="move_right">';
while($row = mysql_fetch_array($log2)){
echo '<div class="LibrarySectsShelf_Book" style="background-color:'.$Color.'"
title="Author: '.$row['bbookauthor'].'">'.$row['bbookname'].'</div>';
if($i%5==0)
{
echo '</div><div class="move_right">';
}
$i++;
}
echo '</div></div></div></a>';
The above code uses <div class="move_right"> ... </div> to divide elements in group of 5 so as to display each group in a new column.
CSS (.move_right)
.move_right{
display:inline-block;
vertical-align:top;
}
Fiddle of how the generated HTML's output will be
I'll provide you with 2 solutions here, PHP and CSS, as #ariel has already contributed a jQuery solution, since I always like to be JS independent, and also it will save you, using a third party script, along with jQuery Library (If you aren't using jQuery), I chosed PHP first, and than the CSS one which may be less compatible in terms of IE.
If you want to achieve that using PHP, you need to alter your loop and set a counter, which will break..
Assume that we are having an array of elements, and we want to set just like you need it..
<div class="wrapper">
<ul>
<?php
$arr = array('1','2','3','4','5','6','7','8','9','10','11','12','13','14','15');
$counter = 0;
foreach ($arr as $value) {
if($counter%5==0 && $counter != 0){ echo "</ul><ul>";}
?>
<li><?php echo $value; ?></li>
<?php
$counter++;
}
?>
</ul>
</div>
Here, am using a counter variable which am incrementing at the end of the loop, the line over here $counter%5==0 in if condition states that if the loop counter is divisible by 5, add </ul><ul>, hence, this will generate a group of ul which are floated to left.. consisting of 5 li each.
Demo - Fiddle Code
CSS
* {
margin: 0;
padding: 0;
-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
box-sizing: border-box;
}
.wrapper {
height: 150px;
margin: 50px;
border: 1px solid #eee;
}
ul {
float: left;
list-style-type: none;
}
ul li {
height: 30px;
width: 150px;
background: tomato;
border: 1px solid #515151;
}
Now as you said that but after the number of contents is more than 5 the height becomes greater than that of the div hence if you apply the same logic in your markup, it will force the div to start another column.
Demo - Fiddle Code
<a class="LibSectOpen">
<span style="display:none" class="SectionName"><?php $value; ?></span>
<div class="LibrarySects"><div class="LibrarySectsHeader">Whatever</div>
<div class="LibrarySectsShelf">
<div class='inner_wrap'>
<?php
$arr = array('1','2','3','4','5','6','7','8','9','10','11','12','13','14','15');
$counter = 0;
foreach ($arr as $value) {
if($counter%5==0 && $counter != 0){ echo "</div><div class='inner_wrap'>";}
?>
<div class="LibrarySectsShelf_Book" title="Author:">Whatever <?php echo $value; ?></div>
<?php
$counter++;
}
?>
</div>
</div>
</div>
</a>
Doing the same with CSS, you can use column-count property, but as far as IE is concerned, it will make a mess.. though if you're interested in the solution, than here you go...
Demo
HTML
<ul>
<li>1</li>
<!-- More incremented li -->
</ul>
CSS
ul {
list-style-type: none;
-moz-column-count: 3;
-webkit-column-count: 3;
column-count: 3;
}
For Multi Column Support Reference
My solution involves jQuery and the plugin Columnizer.
Here's the working fiddle: http://jsfiddle.net/bortao/qGfsr/
The code is very simple:
$('.LibrarySectsShelf').columnize({
width: 166,
height: 150,
doneFunc: function () {
$('.LibrarySectsShelf_Book').removeClass('hidden');
}
});
The only change in your css is this new class:
.hidden {
visibility: hidden
}
Which should be added to every LibrarySectsShelf_Book. This is solely to prevent the flickering of the unorganized items. The class is removed when the columnization is complete.
Easy.
.LibrarySectsShelf {writing-mode: vertical-lr;}
.LibrarySectsShelf_Book {display: inline-block;}
Works in every browser I tested, despite wiki pages claiming otherwise, and it's been around since IE8.
Solution using only CSS
The best way of doing this, is using CSS3 flex boxes like this:
Here is how:
In the CSS add these 3 lines in .LibrarySectsShelf{ ... }
.LibrarySectsShelf {
display: flex; // to add
flex-flow: column wrap; // to add
align-content: flex-start; // to add
... // the rest of your code
}
and 1 line in .LibrarySectsShelf_Book{ ... }
.LibrarySectsShelf_Book{
flex: 0 0 23px;
... // the rest of your code
}
Cross browser support
Please note that since Flex box is a new feature in CSS3, you may have to add some browser prefixes like -webkit-, -moz- and -ms- to let it work properly in all major browsers.
Also note that the flex box wrap feature is only available in Firefox 28 and newer.
A working cross-browser example is available on http://jsfiddle.net/29Cmz/
Why Flexbox
Because it is very flexible, it will fill up all the available space and you don't have to hardcode the number of rows in PHP/JavaScript.
I believe this may be helpful HTML list elements top to bottom, then left to right
The jsfiddle shows that if you want to do this with css you can use css columns. Otherwise an answer below links to a js plugin to achieve this. Alternatively you could just do the positioning when you create the content in PHP if this is possible.
It seems to me that you dont need the complete width of your main container.
Why don't you just add a fixed width to both categories and set them to display:inline; or display:inline-block (still messing these two up... sry).
If you want to determine it dynamically, you could check weather the height of your main container is sufficient for both categories. If this is not the case you could set the css attributes of both categories (I srsly hope for you they have the same css class ;) with
$('.your-class').css({'width':'250px', 'display':'inline'});
I think this should do the magic.
EDIT: Ahh sry. didint see your code... Never the less it should work this way ;)
First of all . Don't put div in a tag .
Then you can find array_chunk php function .
So What you need to do.
It will be better if you use PDO .
PDO fetch all will return array;
<?php
$chunkSize = 5; // or any other value you need
$chunks = array_chunk($result_array,$chunkSize);
foreach($chunks as $links_array):?>
<div class="move_right">
<?php foreach($links_array as $link):?>
<!-- your link code -->
<?php endforeach; ?>
</div>
<?php endforeach ?>
The following code detects the end of the div and creates a new column using css.
var col = 1;
jQuery(
function($)
{
$('#flux').bind('scroll', function()
{
if($(this).scrollTop() +
$(this).innerHeight()
>= $(this)[0].scrollHeight)
{
$("#yourdiv").css("-moz-column-count",col);
$("#yourdiv").css("-webkit-column-count",col);
col++;
}
})
}
);
Tons of great answers here, I vote the javascript/CSS ONLY solution because.
1) the PHP stays solely responsible for getting data to screen ( re use the same php logic for new presentations in the future )
2) The Javascript and CSS can be flexible to provide personalised markup arrangement per device, browser and view size
DEMO : http://jsfiddle.net/9Bc76/1/
Markup - Let PHP just generate the items and forget about presentation.
<div class="container">
<div class="item">An Item</div>
<div class="item"> An Item</div>
<div class="item">An Item</div>
....
Javascript to wrap the elements ( here is a hardcoded per 5 'items' ) - making use of the jquery selector and wrapAll method.
var items = $(".item");
for(var i = 0; i < items.length; i+=5) {
items.slice(i, i+5).wrapAll('<div class="wrapper"></div>');
}
CSS to layout
.wrapper { display:inline-block; float:left; }
/* clear the float so the container keeps 'containing' */
.container:last-child:after {
clear:both; display:block;visibility:hidden;
height:0; content:"."; }
That's it.
More, If we need our 'wrap count' to be dynamic, we can do some calculation based on the height of the .item and the height of .container to get the desired 'wrap' count.
Lets say the container has a fixed height that is not allowed to grow;
.container { height: 300px; width: 100%; overflow: hidden; }
Javascript can find the 'wrap count interval' dynamically ( find how may items fit in the container height }
var containerheight = $(".container").height(),
itemheight = $(".item").height();
var wrapinterval = Math.floor(containerheight/itemheight);
Now we can use
var items = $(".item");
for(var i = 0; i < items.length; i+=wrapinterval) {
items.slice(i, i+wrapinterval).wrapAll('<div class="wrapper"></div>');
}
DEMO with dynamic wrap interval - http://jsfiddle.net/2paNY/2/
APologies to fellow SO'ers if this contains parts already answered in one way or another, I just got into typing away
Just Copy and paste this piece of code and try at your end and use the logic.
<?php
for($i = 1; $i <= 20; $i++){
if($i % 5 == 1){
echo '<div style="float:left;">';
}
echo '<div class="LibrarySectsShelf_Book" style="background-color:'.$Color.'"
title="Author: '.$row['bbookauthor'].'">'.$row['bbookname'].'</div>';
if($i % 5 == 0){
echo '</div>';
}
}
?>

How change content value of pseudo :before element by Javascript [duplicate]

This question already has answers here:
Selecting and manipulating CSS pseudo-elements such as ::before and ::after using javascript (or jQuery)
(26 answers)
Closed 2 years ago.
I have the grap constructured by CSS, which is dynamically changes by JS. I show graph max value by pseudo element as:
.graph:before {
content:""; //value that want set by JS
position:absolute;
top:0;
left:0;
}
That's why I need to set this value by JS. I tried $(".graph:before").css("content", hh); but it didn't help. How to get that value?
I hope the below snippet might help, you can specify the content value you want via JS using the CSS attr() function.
Below you have two options: to use JavaScript or jQuery:
jQuery:
$('.graph').on('click', function () {
//do something with the callback
$(this).attr('data-before','anything'); //anything is the 'content' value
});
JavaScript:
var graphElem = document.querySelector('.graph');
graphElem.addEventListener('click', function (event) {
event.target.setAttribute('data-before', 'anything');
});
CSS:
.graph:before {
content: attr(data-before); /* value that that refers to CSS 'content' */
position:absolute;
top: 0;
left: 0;
}
Update (2018): as has been noted in the comments, you now can do this.
You can't modify pseudo elements through JavaScript since they are not part of the DOM. Your best bet is to define another class in your CSS with the styles you require and then add that to the element. Since that doesn't seem to be possible from your question, perhaps you need to look at using a real DOM element instead of a pseudo one.
You can use CSS variable
:root {
--h: 100px;
}
.elem:after {
top: var(--h);
}
let y = 10;
document.documentElement.style.setProperty('--h', y + 'px')
https://codepen.io/Gorbulin/pen/odVQVL
I believe there is a simple solution using the attr() function to specify the content of the pseudo element. Here is a working example using the 'title' attribute, but it should work also with custom attributes.:
document.getElementById('btn_change1').addEventListener("click", function(){
document.getElementById('test_div').title='Status 1';
});
document.getElementById('btn_change2').addEventListener("click", function(){
document.getElementById('test_div').title='Status 2';
});
#test_div {
margin: 4em;
padding:2em;
background: blue;
color: yellow;
}
#test_div:after {
content:attr(title);
background: red;
padding:1em;
}
<button id='btn_change1'>Change div:after to [Status 1]</button>
<button id='btn_change2'>Change div:after to [Status 2]</button>
<div id='test_div' title='Initial Status'>The element to modify</div>
People who are still looking some solution of same problem, it is doable as follows using jQuery:
<button id="changeBefore">Change</button>
<script>
var newValue = '22';//coming from somewhere
var add = '<style>.graph:before{content:"'+newValue+'"!important;}</style>';
$('#changeBefore').click(function(){
$('body').append(add);
});
</script>
This example illustrate that on clicking button: changeBefore , the value for .graph:before will change as per new dynamic coming value for it.
For more description about changing of :before or :after element style or getting its content:
Lets suppose your HTML is like this:
<div id="something">Test</div>
And then you are setting its :before in CSS and designing it like:
#something:before{
content:"1st";
font-size:20px;
color:red;
}
#something{
content:'1st';
}
Please notice I also set content attribute in element itself so that you can take it out easily later.
Now there is a button clicking on which, you want to change the color of :before to green and its font-size to 30px. You can achieve that as follows:
Define a css with your required style on some class .activeS :
.activeS:before{
color:green !important;
font-size:30px !important;
}
Now you can change :before style by adding the class to your :before element as follows:
<button id="changeBefore">Change</button>
<script>
$('#changeBefore').click(function(){
$('#something').addClass('activeS');
});
</script>
If you just want to get content of :before, it can be done as:
<button id="getContent">Get Content</button>
<script>
$('#getContent').click(function(){
console.log($('#something').css('content'));//will print '1st'
});
</script>
I hope it helps
I had a similar problem, but with icons. I needed to switch the play and pause icons for an audio player in html5.
The problem here was that HTML, CSS and jQuery all interpret differently the "content" values to show icons, due to the use of \ symbol.
So the best workaround is to delete and re-create the node. Here's my code:
<ul class="list list--buttons">
<li><i class="fa fa-step-backward"></i></li>
<li><i class="fa fa-play"></i></li>
<li><i class="fa fa-step-forward"></i></li>
</ul>
And the script
<script type="text/javascript">
$(
function(){
var aud = $('audio')[0];
$('.playpause').on('click', function(e){
e.preventDefault();
if (aud.paused) {
aud.play();
/* from play icon to pause icon */
$('.playpause .fa-play').remove();
$('.playpause').append('<i class="fa fa-pause"></i>');
}
else {
aud.pause();
/* from play icon to pause icon */
$('.playpause .fa-pause').remove();
$('.playpause').append('<i class="fa fa-play"></i>');
}
})
$('.next').on('click', function(e){
e.preventDefault();
aud.src = '{$content:audio-file}';
})
$('.previuos').on('click', function(e){
e.preventDefault();
aud.src = '{$content:audio-file}';
})
aud.ontimeupdate = function(){
$('.progress').css('width', aud.currentTime / aud.duration * 100 + '%')
}
})
</script>
Hope it helps!
You can use document.styleSheets to modify pseudo selector cssRules
document.styleSheets[0].cssRules[0].style.content = '"111"';
If you use something like an onoffswitch and want to translate the css content attribute with i18next then you can use one of the i18next Framework example from github (i18next Jquery Framework) and then you extended the function with this code:
var before = i18next.t('onoffswitch.before');
var after = i18next.t('onoffswitch.after');
$('.onoffswitch-inner')
.attr('data-before', before )
.attr('data-after', after );
and the css code must be this:
.onoffswitch-inner:before {
content: attr(data-before);
padding-left: 10px;
background-color: #65AFF5; color: #FFFFFF;
}
.onoffswitch-inner:after {
content: attr(data-after);
padding-right: 10px;
background-color: #EEEEEE; color: #999999;
text-align: right;
}

Categories

Resources