How can I change css from php side? - javascript

Basically, I want to add an additional class when a certain IF condition is met.
<?php
if($type == 'NEW')
{
$('#'+day+s).addClass('new');
}
if($type == 'USED')
{
$('#'+day+s).addClass('used');
}
?>

You would need to do it through JavaScript / jQuery inside of a PHP conditional.
You can either close your PHP tags while leaving the conditional open:
<?php
if($type == 'NEW')
{
?>
<script>$('#'+day+s).addClass('new');</script>
<?php
}
if($type == 'USED')
{
?>
<script>$('#'+day+s).addClass('used');</script>
<?php
}
?>
Or echo() out the <script> tags from within PHP:
<?php
if($type == 'NEW')
{
echo "<script>$('#'+day+s).addClass('new');</script>";
}
if($type == 'USED')
{
echo "<script>$('#'+day+s).addClass('used');</script>";
}
?>
Having said that, you'd be better off simply altering your logic to output classes based on your conditionals. That way you would simply need to add a regular CSS rule for each class. The right rule would be selected based on which class was outputted.

It should be directly in your HTML :
<div class="<?php if ($type == 'NEW') echo 'new';?>"></div>

You have to assign your calss name in a variable and simply give that to your corresponding MHTL.
<?php
if($type == 'NEW')
{
$style = "class_name for if"; //eg:- new
}
if($type == 'USED')
{
$style = "class_name for else"; //eg:- used
}
?>
//html element
for eg:
<p id="days" class="<?php echo $style;?>"></p>

several ways to do that and depends also in your code
<!-- Assignment inline -->
<div class="<?= $type === 'NEW' ? 'newClass' : 'usedClass'?>"></div>
<!-- Assignment previous -->
<?php
$class = 'defaultClass';
if ($type === 'NEW') { $class = 'newClass'; }
if ($type === 'USED') { $class = 'usedClass'; }
?>
<div class="<?=$class?>"></div>
<!-- Assignment in script -->
<?php $class = $type === 'NEW' ? 'newClass' : 'usedClass'; ?>
<script>
$(document).ready(function(){
$('#'+day+s).addClass('<?= $class ?>');
});
</script>

You can put the if condition of PHP inside class attribute directly. No need to do any method or js for this. You can use the logic as below:
<div class="<?php if($type == 'NEW'){ echo 'new';} else if($type == 'USED'){ echo 'used'; } ?>"></div>

Related

Refreshing owl-carousel2 on dynamic image load

I need to show a carousel of images inside a <td> in a dataTable dynamically, based on a array of images provided by PHP. Right now all I got is a stack of all the images.
Searching online I undestood I have to reload the carousel AFTER all the images in the td are loaded, but I don't know how.
Here's my html:
<?php foreach ($intest as $int) {
if (is_array($int['cartella'])) {
foreach ($int['cartella'] as $cartella){ ?>
<td><div class="owl-carousel owl-theme prova" >
<?php $files = "images/" . Yii::app()->session['dominio']."/".$row['num_registraz']."/". $cartella."/";
//CVarDumper::dump($file);
if(is_dir($files)){
if ($dh = opendir($files)) {
while (false !== ($file = readdir($dh))) {
if($file == '.' || $file == '..'){
continue;
}
$ext = strtolower(pathinfo($file, PATHINFO_EXTENSION));
if ($ext=='jpg' || $ext=='jpeg' || $ext=='png' || $ext=='gif'){?>
<img class="mia" src="<?= $files.$file ?>">
<?php } else if ($ext == 'pdf'){ ?>
<div>File PDF</div>
<?php } else if ($ext == 'doc' || $ext =='docx') {?>
<div>File DOC</div>
<?php } else {?>
<div>Unsupported file</div>
<?php } } } }else if (!is_dir($files)){ ?>
No foto
<?php } } } } } ?>
</div></td>
And here's the Javascript i tried to reload it
var car = $('#prova');
car.on('load', function(){
car.trigger('destroy.owl.carousel');
car.owlCarousel({
'items':1
});
});
Any help would greatly appreciated

Should be simple (but it isn't): Javascript snippet inside PHP

I have coded in PHP and JS for a while, but I don't do it often, and so I've been snagged by something that should be simple, but it's giving me fits. And none of the answers I've found here have solved the problem.
I have JS slideshow code that is inserted into a WordPress page when multiple images named [pagename]1,2,3...png are present in the images folder. I've struggled to get the code to read the folder, and now it does. But the JS slideshow is not working on the "Menu" page, while the exact same code is working on the "Home" page. The only difference between the two is that the Menu code tests whether images are present in the images folder. (They are.)
This first part of the code is, I feel certain, correct. The second piece of code is where the issue is. Why is the JS not starting my slideshow? It should. The code reads properly on the page.
<?php
$uploads = wp_upload_dir();
$x = 1;
$poname = $post->post_name;
if ($dir = opendir('/home/rowlandwilliams/public_html/lepeep/wp-content/themes/twentythirteen-child/images')) {
$images = array();
while (false !== ($file = readdir($dir))) {
if ($file != "." && $file != "..") {
$images[] = $file;
asort($images);
}
}
closedir($dir);
}
And this is where I think the problem is:
foreach($images as $image) {
$subimg = substr($image, 0, -5);
if ($subimg == $poname) {
if ($x == 1) {
echo "<script type='text/javascript'>
function cycleImages(container) {
var $active = container.find('.active');
var $next = ($active.next().length > 0) ? $active.next() : container.find('img:first');
$next.css('z-index',2);
$active.fadeOut(1500,function() {
$active.css('z-index',1).show().removeClass('active');
$next.css('z-index',3).addClass('active');
});
$(document).ready(function() {
setInterval(function(){cycleImages($('#page-cycler'))}, 2000);
})
}
</script>"; ?>
<div class="cycler" id="page-cycler">
<?php $actstat = 'class="active"'; ?>
<?php $x++; ?>
<?php } else { ?>
<?php $actstat = ''; ?>
<?php } ?>
<img <?php echo $actstat; ?> src="<?php bloginfo('stylesheet_directory'); ?>/images/<?php echo $image; ?>">
<?php } ?>
<?php } ?>
</div><!-- #page-cycler -->
http://rowlandwilliams.com/lepeep/menu/
This is where your problem is:
echo "<script type='text/javascript'>
function cycleImages(container) {
var $active = container.find('.active');
var $next = ($active.next().length > 0) ? $active.next() : container.find('img:first');
$next.css('z-index',2);
$active.fadeOut(1500,function() {
$active.css('z-index',1).show().removeClass('active');
$next.css('z-index',3).addClass('active');
});
$(document).ready(function() {
setInterval(function(){cycleImages($('#page-cycler'))}, 2000);
})
}
</script>";
When you use " to echo with, php will parse all $var...
So the variable $activeand $next is being echoed from php, which doesn't look like it's set anywhere in your code. The solution would either be to change variable names from $active to active or to use single quotes ' instead of double quotes "
Using single quotes (') will tell PHP not to parse any variables inside the echo, while using double quotes (") will.
Try using ' quotes, and replace any ' quotes inside the JS with " quotes.
echo '<script type="text/javascript">
function cycleImages(container) {
var $active = container.find(".active");
var $next = ($active.next().length > 0) ? $active.next() : container.find("img:first");
$next.css("z-index",2);
$active.fadeOut(1500,function() {
$active.css("z-index",1).show().removeClass("active");
$next.css("z-index",3).addClass("active");
});
$(document).ready(function() {
setInterval(function(){cycleImages($("#page-cycler"))}, 2000);
})
}
</script>';
Your code is mess, I have rewrite your code for more clean, maybe. Since you there is no php code inside your javascript, don't try to use echo it will make your code even mess and as #Arian mentioned, $active and $next will be work as php variable.
foreach($images as $image):
$subimg = substr($image, 0, -5);
if ($subimg == $poname):
if ($x == 1): ?>
<script type='text/javascript'>
function cycleImages(container) {
var $active = container.find('.active');
var $next = ($active.next().length > 0) ? $active.next() : container.find('img:first');
$next.css('z-index',2);
$active.fadeOut(1500,function() {
$active.css('z-index',1).show().removeClass('active');
$next.css('z-index',3).addClass('active');
});
$(document).ready(function() {
setInterval(function(){cycleImages($('#page-cycler'))}, 2000);
})
}
</script>
<div class="cycler" id="page-cycler">
<?php
$actstat = 'class="active"';
$x++;
else:
$actstat = '';
endif; ?>
<img <?= $actstat; ?> src="<?php bloginfo('stylesheet_directory'); ?>/images/<?= $image; ?>">
<?php endif; ?>
<?php endforeach; ?>
</div><!-- #page-cycler -->

JavaScript and PHP sessions

My login.php looks like:
if ($count == 1){
$_SESSION['username'] = "1";
if (isset($_SESSION['username'])){
ob_start();
$url = 'main.php';
while (ob_get_status())
{
ob_end_clean();
}
header( "Location: $url" );
}
}
else {
$_SESSION['username']='';
}
and when I succesfully log in, main.php redirects me to login.php instead of running the game loop.
<?php
if(!(isset($_SESSION['username']) && $_SESSION['username']!='')) {
echo "<script>window.location.href=\"login.php\"</script>";
}
else {
echo "<script defer>reload();</script>";
}
?>
Thank you.
try instead
<?php
session_start();
if(empty($_SESSION['username'])) {
echo "<script>window.location.href=\"login.php\"</script>";
}
else {
echo "<script defer>reload();</script>";
}
Emptychecks
"" (an empty string)
0 (0 as an integer)
0.0 (0 as a float)
"0" (0 as a string)
NULL
FALSE
array() (an empty array)
$var; (a variable declared, but without a value)
or do $_SESSION['username']=='' check.
I think your main php code should change like this..
<?php
if(!(isset($_SESSION['username']) && $_SESSION['username']=='')) {
echo "<script>window.location.href=\"login.php\"</script>";
}
else {
echo "<script defer>reload();</script>";
}
?>
here you are checking $_SESSION['username']!=''
Need to change that to..
if(!(isset($_SESSION['username']) && $_SESSION['username']==''))

Executing Javascript with php and echo some vars

I am trying to execute a simple javascript file with if and else in php. So far it is working but i have an issue.. See the example bellow.
<?
$varone = "Popup One";
$vartwo = "Popup Two";
if ($_GET['myrequest'] == "")
{
echo <<<html
<script>
alert($varone);
</script>
html;
}else{
echo <<<html
<script>
alert($vartwo);
</script>
html;
}
?>
So i want to pass my php variables inside each alert! Or is there any other simply way to execute my javascript and pass my php variables in javascript?
Thank you!!!
Try
<?php
$varone = "Popup One";
$vartwo = "Popup Two";
if ($_GET['myrequest'] == "")
{
echo " <script>
alert('".$varone."');
</script>";
}else{
echo "<script>
alert('".$vartwo."');
</script> ";
}
?>
To Keep separate your JavaScript and PHP try this
<?php
$varone = "Popup One";
$vartwo = "Popup Two";
if ($_GET ['myrequest'] == "") {
?>
<script>
alert('<?php echo $varone; ?>');
</script>
<?php
} else {
?>
<script>
alert('<?php echo $vartwo; ?>');
</script>
<?php
}
?>
I think you are just missing quotes around your variables inside the alerts.
Try this:
<?
$varone = "Popup One";
$vartwo = "Popup Two";
if ($_GET['myrequest'] == "")
{
echo <<<html
<script>
alert('$varone');
</script>
html;
} else {
echo <<<html
<script>
alert('$vartwo');
</script>
html;
}
?>
You may have spotted this javascript error if you had looked in your browser's javascript console, which is very helpful for debugging. Google for how to open the javascript console in whichever web browser you use.
i don't know what you're trying to achieve but i think that if you want to pass some var from php to js the best approach would be use $.ajax , but this depend on what your trying to do or in this case maybe something like this should do the tricks.
<?php
if($_GET['myrequest'] == ""){
$alertVar = "popupone";
}
else{
$alertVar = "popuptwo";
}
?>
<script>
alert('<?php echo $alertVar ?>');
</script>
You have few choices as seen in the answers.
<?php
$varone = "Popup One";
$vartwo = "Popup Two";
?>
<script>
<?php if ($_GET['myrequest'] == ""):?>
alert('<?php echo $varone; ?>');
<?php else: ?>
alert('<?php echo $vartwo; ?>');
<?php endif; ?>
</script>

How to compare like "x != a OR b" in JavaScript?

Wondering how to add in js script a three more !== or statements. The following script was provided as a spectacular answer by jsfriend00 but the problem is I made the mistake of not mentioning there's three more textareas unaccounted for. I'm stuck with the javascript on the remaining or !== conditions. In the following script how to take say !== to each of the following var obj?
//VIEW FILE for private networking stream between admin and clientele:
<?php if(!defined('BASEPATH')) exit('No direct script access allowed'); ?>
<html>
<title>Chat</title>
<head>
<?php echo smiley_js(); ?>
</head>
<body>
<?php echo form_open('controller/function');?>
Reload chat<?php echo form_submit('reload','reload chat');?>
<?php echo form_close();?>
<?php if(isset($user_query)): foreach($user_query->result() as $row):?>
<p>Created at: <?php echo $row->created_at; ?> </p>
<p>Updated at: <?php echo $row->updated_at; ?> </p>
<p><label for="update"> <?php echo $username_sess.' said'?>:<span class="optional"></span></label>
<textarea name="update" id="update" rows="7" cols="30"><?php echo $row->clt_rep_stream ?></textarea>
<?php echo form_open('controller/function');?>
<?php echo form_hidden('user_id',$row->user_id) ?>
<p><label for="adm_update">reply to client:<span class="optional"></span></label>
<textarea name="adm_update" id="adm_update" rows="7" cols="30"> </textarea>
<?php echo form_error('adm_update'); ?>
</p>
<?php echo form_submit('submit','reply');?>
<?php echo form_close();?>
<?php echo form_open('controller/function'); ?>
<?php echo form_hidden('user_id',$row->user_id) ?>
<p>Replied at: <?php echo $row->adm_created_at; ?> </p>
<p>Updated at: <?php echo $row->adm_updated_at; ?> </p>
<p><label for="reupdate"> <?php echo $username_adm_sess.' replied:'?><span class="optional"></span></label>
<textarea name="reupdate" id="reupdate" rows="7" cols="30"><?php echo $row->adm_rep_stream ?> </textarea>
<p>
<?php echo form_submit( 'submit', 'update reply'); ?>
</p>
<?php echo form_close(); ?>
<?php endforeach; ?>
<?php endif; ?>
<script>
function autoRefresh(refreshPeriod) {
var obj = document.getElementById("create");
var obj_two = document.getElementById("update");
var obj_three = document.getElementById("delete");
var obj_four = document.getElementById("reload");
function refreshIfSafe() {
if (document.activeElement !== obj) {
window.location.reload();
} else {
setTimeout(refreshIfSafe, refreshPeriod);
}
}
setTimeout(refreshIfSafe, refreshPeriod);
}
autoRefresh(2 * 1000);
</script>
</body>
</html>
I tried the following but didn't work:
if(document.activeElement !==(obj || obj_two))
I tried the following after Brad's post which partially worked but any update or replies after the first two and the following js is rendered null and void which is really confusing:
if(document.activeElement !== obj && document.activeElement !== obj_two)
Each condition is separate. Treat it as such.
(document.activeElement !== obj) && (document.activeElement !== obj_two) && ...
You could also do this in a loop if your elements weren't explicitly called out like they are, but I don't know how this would fit in your code, as I don't know what your actual code looks like.
Untested, but should work:
<script>
function autoRefresh(refreshPeriod) {
var elementArray = [
document.getElementById("create"),
document.getElementById("update"),
document.getElementById("delete"),
document.getElementById("reload")
];
function refreshIfSafe() {
if (elementArray.indexOf(document.activeElement) !== -1) {
window.location.reload();
} else {
setTimeout(refreshIfSafe, refreshPeriod);
}
}
setTimeout(refreshIfSafe, refreshPeriod);
}
autoRefresh(2 * 1000);
</script>
Or
<script>
function autoRefresh(refreshPeriod) {
var elementArray = ["create", "update", "delete", "reload"];
function refreshIfSafe() {
if (document.activeElement && elementArray.indexOf(document.activeElement.id) !== -1) {
window.location.reload();
} else {
setTimeout(refreshIfSafe, refreshPeriod);
}
}
setTimeout(refreshIfSafe, refreshPeriod);
}
autoRefresh(2 * 1000);
</script>
You can try ... no don't !
if(!(document.activeElement in [obj,obj_two])){
// ...
}
By the way, when comparing objects, you actually compare their references adress in memory ... so '!=' is enough.

Categories