Problem changing background image using Javascript - javascript

I'm trying to change the background image of a link when it is clicked via Javascript. I five tabs and when the user clicks on a tab, I want the background image of that tab to change to a plain white image. Where as the other four tabs should be changed to a grey image.
So my CSS is as follows:
.listingindex li a {
background:url(../images/tabe-nomal.jpg) left top no-repeat;
color:#333333;
display: inline-block;
text-decoration:none;
width:229px;
padding:14px 0px 14px 10px;
}
.listingindex li a:hover {
background:url(../images/tabe-over.jpg) left top no-repeat;
}
and my code looks like this:
<div class="listingindex">
<?php
$catId = get_cat_id('featured');
$childOf = 'child_of='.$catId;
$subCats = get_categories($childOf);
// Slice array so only 5 categories can be displayed.
$subCats = array_slice($subCats, 0, 5);
foreach ($subCats as $value) {
$subCatsStr .= $value->cat_ID.'|';
}
foreach ($subCats as $subCat) {
?>
<ul>
<li><a id="tab_<?=$subCat->cat_ID?>" href="javascript:toggle(<?=$subCat->cat_ID?>,'<?=$subCatsStr?>')"><?=$subCat->name?></a></li>
</ul>
<ul id="thumbnails_<?=$subCat->cat_ID?>" class="listingarea">
<?php $query = new WP_Query('category_name='.$subCat->name.'&posts_per_page=9');
while( $query->have_posts() ) : $query->the_post();?>
<li>
<a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>">
<?
$id = $post->ID;
$filename = $_SERVER["DOCUMENT_ROOT"].'/xxxxxxx/xxxxxx/xxxxx/xxxxxx/images/thumbnails/image_'.$id.'.jpg';
if (file_exists($filename)) {
?><img src="<?php echo $templateDir; ?>/images/thumbnails/image_<?=$id;?>.jpg" alt="Image_<?=$id;?>" /><?
}else{
?><img src="<?php echo $templateDir; ?>/images/thumbnails/no_image.jpg" alt="No Image" /><?
}?>
</a>
</li>
<?php endwhile; ?>
</ul>
<?}?>
</div>
Lastly my JS looks like this:
function toggle(catID, subCatsStr) {
document.getElementById('thumbnails_'+catID).style.display = "block";
document.getElementById('tab_'+catID).style.backgroundImage = "url(/images/tabe-over.jpg)";
subCatsArr = subCatsStr.split('|');
for (i = 0; i <= subCatsArr.length - 2; i++){
if (subCatsArr[i] != catID){
document.getElementById('thumbnails_'+subCatsArr[i]).style.display = "none";
document.getElementById('tab_'+catID).style.backgroundImage = "url(images/tabe-nomal.jpg) left top no-repeat";
}
}
}
At the moment, this code simply removes the grey image (tabe-nomal.jpg) when a tab is clicked.
Any help appreciated.
Regards...

Looks like your backgroundImage urls might not be correct -- try using the same path (../images/..) as in your initial css rule

To solve the problem in the end I had to specify the full path name:
document.getElementById('tab_'+catID).style.backgroundImage = "url(http://www.xxxxxx.ie/xxxxxxx/wp-content/themes/xxxxxxx/images/tabe-over.jpg)";
Not sure why, but this solved the problem. Its a Wordpress theme so maybe this had something to do with it.

Related

How to stop the width of an image from stretching inside a div?

I have an html form that takes input from a user and php code that takes the input from a specified folder. It then retrieves every image in that folder and displays it in a slideshow.
The problem is that the width of the image stretches and makes it look terrible. I tried the object-fit tactic among other tactics I found online but none of them seem to work.
How do I maintain the aspect ratio of the images inside the cycle-slideshow?
<html>
<head>
<style = "text/css">
</style>
</head>
<body>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script src="http://malsup.github.com/jquery.cycle2.js"></script>
<?php
$images = array();
$directory = 'images '.$_POST["name"];
if ($handle = opendir($directory)) {
while (false !== ($file = readdir($handle))) {
if (preg_match("/\.png$/", $file)) $images[] = $file;
elseif (preg_match("/\.jpg$/", $file)) $images[] = $file;
elseif (preg_match("/\.jpeg$/", $file)) $images[] = $file;
elseif (preg_match("/\.gif$/", $file)) $images[] = $file;
}
shuffle($images);
closedir($handle);
}
?>
<div class="cycle-slideshow">
<?php
for($i= 0; $i < 3; $i++) {
foreach ( new DirectoryIterator($directory) as $item ) {
if ($item->isFile()) {
$path = $directory . '/' . $item;
echo '<img src="' . $path . '" class="displayed"
height= "512px"
object-fit= "contain"
width = "75%"
display: "block"
margin: "auto"
border= "3px solid #73AD21" />';
}
}
}
?>
</div>
</body>
</html>
You should remove width = "75% because you already have height initialized. You can also add padding to the images in your CSS file. Note: For using padding you should actually use box-sizing: border-box. By using border-box you actually add that padding within dimensions of of your box and preventing it to change widht or height of it.
I didn't test it but hope i understood you question.

Yii Register JS Variables

I am using HumHub, based on Yii, and trying to set a JS variable with a URL extracted from a function that enriches text.
Currently, the variable doesn't seem to be getting set in the model, so I haven't even really begin to work on the script.
It should fetch OpenGraph data eventually, but I can't even get the URL to the script I intend to debug and use.
Base enrichText function
/**
* Converts an given Ascii Text into a HTML Block
* #param boolean $allowHtml transform user names in links
* #param boolean $allowEmbed Sets if comitted video links will embedded
*
* Tasks:
* nl2br
* oembed urls
*/
public static function enrichText($text, $from = 'default', $postid = '')
{
if ( $from == 'default' ) {
$maxOembedCount = 3; // Maximum OEmbeds
$oembedCount = 0; // OEmbeds used
// Parse bbcodes before link parsing
$text = self::parseBBCodes($text);
$text = preg_replace_callback('/(?<!\])(https?:\/\/.*?)(\s|$)(?!\[)/i', function ($match) use (&$oembedCount, &$maxOembedCount) {
// Try use oembed
if ($maxOembedCount > $oembedCount) {
$oembed = UrlOembed::GetOembed($match[0]);
if ($oembed) {
$oembedCount++;
return $oembed;
}
}
$regurl = "/(http|https)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";
// Check if there is a url in the text independently and render to JS var
if(preg_match($regurl, $text, $url)) {
if (!empty($postid)) {
Yii::app()->clientScript->setJavascriptVariable("ourl".$postid, $url[0]);
}
}
return HHtml::link($match[1], $match[1], array('target' => '_blank')).$match[2];
}, $text);
// get user and space details from guids
$text = self::translateMentioning($text, true);
// create image tag for emojis
$text = self::translateEmojis($text);
return nl2br($text);
} else {
// Parse bbcodes before link parsing
$text = self::parseBBCodes($text, $from);
return $text;
}
}
Calling info
<?php
/**
* This view represents a wall entry of a post.
* Used by PostWidget to show Posts inside a wall.
*
* #property User $user the user which created this post
* #property Post $post the current post
*
* #package humhub.modules.post
* #since 0.5
*/
?>
<div class="panel panel-default post" id="post-<?php echo $post->id; ?>">
<div class="panel-body">
<?php $this->beginContent('application.modules_core.wall.views.wallLayout', array('object' => $post)); ?>
<span id="post-content-<?php echo $post->id; ?>" style="overflow: hidden; margin-bottom: 5px;">
<?php print HHtml::enrichText($post->message, 'default', $post->id); ?>
</span>
<a class="more-link-post hidden" id="more-link-post-<?php echo $post->id; ?>" data-state="down"
style="margin: 20px 0 20px 0;" href="javascript:showMore(<?php echo $post->id; ?>);"><i
class="fa fa-arrow-down"></i> <?php echo Yii::t('PostModule.widgets_views_post', 'Read full post...'); ?>
</a>
<div id="opengraph-<?php echo $post->id; ?>" class="opengraph-container">
<div class="opengraph-img-<?php echo $post->id; ?>"></div>
<div class="opengraph-body">
<h2 class="opengraph-heading-<?php echo $post->id; ?>"></h2>
<div class="opengraph-content-<?php echo $post->id; ?>"></div>
</div>
</div>
<?php $this->endContent(); ?>
</div>
</div>
<script type="text/javascript">
console.log('Oembed URL for <?php echo $post->id; ?>: '+ourl<?php echo $post->id; ?>);
// ... etc
Update I was able to pass the variable by adding a script to the end of the text. Very, very dirty method. I was hoping for something much cleaner. :(
/**
* Converts an given Ascii Text into a HTML Block
* #param boolean $allowHtml transform user names in links
* #param boolean $allowEmbed Sets if comitted video links will embedded
*
* Tasks:
* nl2br
* oembed urls
*/
public static function enrichText($text, $from = 'default', $postid = '')
{
if ( $from == 'default' ) {
$maxOembedCount = 3; // Maximum OEmbeds
$oembedCount = 0; // OEmbeds used
// Parse bbcodes before link parsing
$text = self::parseBBCodes($text);
$text = preg_replace_callback('/(?<!\])(https?:\/\/.*?)(\s|$)(?!\[)/i', function ($match) use (&$oembedCount, &$maxOembedCount) {
// Try use oembed
if ($maxOembedCount > $oembedCount) {
$oembed = UrlOembed::GetOembed($match[0]);
if ($oembed) {
$oembedCount++;
return $oembed;
}
}
return HHtml::link($match[1], $match[1], array('target' => '_blank')).$match[2];
}, $text);
// get user and space details from guids
$text = self::translateMentioning($text, true);
// create image tag for emojis
$text = self::translateEmojis($text);
$regurl = "/(http|https)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";
// Check if there is a url in the text independently and render to JS var
if(preg_match($regurl, $text, $url)) {
if (!empty($postid)) {
$text .= '<script type="text/javascript"> var ourl'.$postid.' = \''.$url[0].'\'; </script>';
}
}
return nl2br($text);
} else {
// Parse bbcodes before link parsing
$text = self::parseBBCodes($text, $from);
return $text;
}
}
Update 2: Attempt to grab Opengraph data
Here i attempt to grab the data from opengraph with the supposed set variable in the HHtml::enrichText() return. However I get the error: SyntaxError: expected expression, got '<' jquery.js:1 pointing to the first line of the jquery file, which is the commenting and license of the script.
The script also doesn't show in source code
<?php
/**
* This view represents a wall entry of a post.
* Used by PostWidget to show Posts inside a wall.
*
* #property User $user the user which created this post
* #property Post $post the current post
*
* #package humhub.modules.post
* #since 0.5
*/
?>
<div class="panel panel-default post" id="post-<?php echo $post->id; ?>">
<div class="panel-body">
<?php $this->beginContent('application.modules_core.wall.views.wallLayout', array('object' => $post)); ?>
<span id="post-content-<?php echo $post->id; ?>" style="overflow: hidden; margin-bottom: 5px;">
<?php print HHtml::enrichText($post->message, 'default', $post->id); ?>
</span>
<a class="more-link-post hidden" id="more-link-post-<?php echo $post->id; ?>" data-state="down"
style="margin: 20px 0 20px 0;" href="javascript:showMore(<?php echo $post->id; ?>);"><i
class="fa fa-arrow-down"></i> <?php echo Yii::t('PostModule.widgets_views_post', 'Read full post...'); ?>
</a>
<div id="opengraph-<?php echo $post->id; ?>" class="opengraph-container">
<div class="opengraph-img-<?php echo $post->id; ?>"></div>
<div class="opengraph-body">
<h2 class="opengraph-heading-<?php echo $post->id; ?>"></h2>
<div class="opengraph-content-<?php echo $post->id; ?>"></div>
</div>
<script type="text/javascript">
$(document).ready(function(){
(function() {
var opengraph = "http://bfxsocial.strangled.net/resources/Opengraph/getInfo.php?callback=?";
$.getJSON( opengraph, {
href: ourl<?php echo $post->id; ?>,
format: "json"
})
.done(function( data ) {
console.log('<?php echo Yii::t('PostModule.widgets_views_post', 'Opengraph: Response from: '); ?>'+ourl-<?php echo $post->id; ?>+"\n\n"+data);
var img = $('<img />',{ id: 'og:img-<?php echo $post->id; ?>', src: data['og:image'], alt:'data.title'}).appendTo($('.opengraph-img-<?php echo $post->id; ?>'));
$('.opengraph-heading-<?php echo $post->id; ?>').html(data.title);
$('.opengraph-body-<?php echo $post->id; ?>').html(data.description);
$('#opengraph-<?php echo $post->id; ?>').show();
});
})();
});
</script>
</div>
<?php $this->endContent(); ?>
</div>
</div>
<!-- Opengraph Temp Style -->
<style type="text/css">
.opengraph-container
display: none;
width: 100%;
padding: 3px;
margin: 5px;
background-color: rgba(0,0,0,0.1);
border: 1px solid rgba(150,150,150,0.1);
}
.opengraph-img {
display: block;
min-width: 99%;
max-height: 350px;
margin: 0 auto;
}
.opengraph-body {
width: 99%;
padding-top: 5px;
border-top: 1px solid rgba(0,0,0,0.1);
}
.opengraph-heading {
display: block;
width: 250px;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.opengraph-content {
font-size: 12px;
color: #7F7F7F;
}
</style>
<!-- End: Opengraph Temp Style -->

Images not stacking up in Masonry template?

So apparently my images are not stacking up on top of each other. They are all in straight horizontal rows. Not sure what is wrong. I want the images to be stacked up on top of each other in a fitted Pinterest-like/Masonry grid.
Here's the shortcode I use in my index file:
echo do_shortcode('[nggallery id="1"]');
Here's the code found in my Masonry gallery template file:
<?php
/**
Template Page for the gallery overview
Follow variables are useable :
$gallery : Contain all about the gallery
$images : Contain all images, path, title
$pagination : Contain the pagination content
You can check the content when you insert the tag <?php var_dump($variable) ?>
If you would like to show the timestamp of the image ,you can use <?php echo $exif['created_timestamp'] ?>
**/
?>
<script src="/wp-includes/js/jquery/jquery.masonry.min.js" type="text/javascript"> </script>
<script>
$(function(){
var $container = $('#container');
$container.imagesLoaded( function(){
$container.masonry({
itemSelector : '.box'
});
});
});
</script>
<style>
.brick {
display: block;
margin: 0px 10px 15px 10px;
float:left;
/* width:250px; */
height: auto;
}
</style>
<script>
jQuery( document ).ready( function( $ ) {
$('#wall').masonry({
// options
itemSelector : '.brick',
isAnimated: true,
animationOptions: {
duration: 500,
easing: 'linear',
queue: false}
});
</script>
<?php if (!defined ('ABSPATH')) die ('No direct access allowed'); ?><?php if (!empty ($gallery)) : ?>
<div class="ngg-galleryoverview" id="<?php echo $gallery->anchor ?>">
<div id="wall">
<!-- Thumbnails -->
<?php $i = 0; ?>
<?php foreach ( $images as $image ) : ?>
<div class="brick">
<a class="thickbox" href="<?php echo $image->imageURL ?>" title="<?php echo $image->description ?>" <?php echo $image->thumbcode ?> >
<?php if ( !$image->hidden ) { ?>
<img title="<?php echo $image->alttext ?>" alt="<?php echo $image->alttext ?>" src="<?php echo $image->thumbnailURL ?>" <?php echo $image->size ?> />
<?php } ?>
</a>
</div>
<?php if ( $image->hidden ) continue; ?>
<?php if ($gallery->columns > 0): ?>
<?php if ((($i + 1) % $gallery->columns) == 0 ): ?>
<br style="clear: both" />
<?php endif; ?>
<?php endif; ?>
<?php $i++; ?>
<?php endforeach; ?>
<?php echo $pagination ?>
</div>
</div>
<?php endif; ?>
This is what my gallery looks like on the actual page:
http://steppic.com/original/896e07bdf2f759709b9ccc5f9eea9e28.png
You are calling masonry twice with different parameters.
The first, your container is "#container" and your items are ".box":
var $container = $('#container');
$container.imagesLoaded( function(){
$container.masonry({
itemSelector : '.box'
});
In the second, your container is "#wall" and your items are ".brick", and you left out "});" at the end of your (document).ready
jQuery( document ).ready( function( $ ) {
$('#wall').masonry({
// options
itemSelector : '.brick',
isAnimated: true,
animationOptions: {
duration: 500,
easing: 'linear',
queue: false}
});
}); //this was missing
Pick the correct container and items and it should work
I'm not completely sure as I don't know if you provided the complete CSS, but maybe it will work if you just remove the margin: 0px 10px 15px 10px; for class brick.
On the masonry example page I just adjusted an example by adding this margin to the class item which corresponds to your class brick, and the result looks similar to your screenshot:
Masonry Example
In addition, it looks like you call masonry twice - one time for .container - $container.masonry({..., and a second time for #wall - $('#wall').masonry({...
You could check if it's working like intended when you remove the margin as suggested and maybe also call masonry only once.
Update: Next adjustment you can try is to remove height: auto; from class brick.
I've adjusted a masonry example by adding height: auto to class item: Masonry with height: auto, as you will notice, there are some issues not present when the setting for height is removed: Masonry without height: auto
For masonry reference: http://masonry.desandro.com/options.html

Slide to left ul li via JavaScript

I have this structure:
<div style="background-color:#FFF;height:49px;border-top:1px solid #ef4723;clear:both">
<div id="marka-slider" class="row">
<ul>
<?php if (($references = Reference::getAll())) :
foreach ($references as $r) :
?>
<li>
<img src="<?php echo Reference::getUploadPath() . '/' . $r->mediapath; ?>"
alt="<?php echo $r->title; ?>" title="<?php echo $r->title; ?>"/>
<!-- <?php CVarDumper::dump(array('ref: ' => $r->attributes), 5, 1); ?> -->
</li>
<?php endforeach; ?>
<?php endif; ?>
</ul>
</div>
</div>
JS:
var slider;
$(document).ready(function () {
slider = $('#marka-slider ul li');
setTimeout(function() {
bgscroll('right');
}, 1000);
});
function bgscroll(direction) {
var sign;
if (direction === 'left') {
slider.stop().animate({'background-position': '+=10000'}, 200000, 'linear', bgscroll);
} else {
slider.stop().animate({'background-position': '-=10000'}, 200000, 'linear', bgscroll);
}
But it isn't working. When I check via Firebug, it doesn't give a error. How can I solve it?
DEMO
http://jsfiddle.net/xpVRT/2/
You were animating background image of the li tag, while the images were inside li in the img tags.

Add Swipe Event to my WP jQuery // Slide Show?

I'm wondering how I can add the jQuery / Mobile Swipe event to my Wordpress Slide Show:
I'd like to be able to 'Swipe' through my slides with this using at Mobile.
Slide Show Code // Mark-Up with WP's PHP:
<!-- Top of Page Slider FRAGILE -->
<div id="photo-rotatorWrapper">
<div id="photosubwrap" style="min-height: 280px; max-height: 280px;">
<div id="photo-rotator" style="">
<?php $slide_id=1; ?>
<?php
$featuredPosts = new WP_Query();
$featuredPosts->query("showposts=3");
while ($featuredPosts->have_posts()) : $featuredPosts->the_post();
?>
<div id="slide-<?php echo $slide_id; $slide_id++;?>">
<a href="<?php the_permalink() ?>" class="post-image">
<?php the_post_thumbnail( 'rotator-post-image' ); ?>
<span class="title" style="font-style:italic; color:#999;"><?php the_title(); ?></span>
</a>
</div>
<?php endwhile; ?><!--/close loop-->
<ul id="slide-nav">
<?php $nav_id=1; ?>
<?php while ($featuredPosts->have_posts()) : $featuredPosts->the_post(); ?>
<li>
<a href="#slide-<?php echo $nav_id; ?>">
<span class="thumbnail" style="display:none;">
</span>
<p style="color:#F93; font-family:Georgia, 'Times New Roman', Times, serif; font-size: 18px;"><? the_title(); $nav_id++;?></p>
<div style="">
<!--<?php the_excerpt(); ?>-->
<?php if($text= get_post_meta($post->ID, "slidetext", true)) { ?>
<div class="">
<p style="font-weight: normal; color: #333; font-family: Arial, Helvetica, sans-serif; font-size: 14px;"><?php echo $text; ?></p>
</div>
<?php } //else { print"<div>"; } ?>
</div>
</a>
</li>
<?php endwhile; ?><!--/close loop-->
</ul>
</div>
</div>
</div>
<!-- End Top page Slider FRAGILE -->
Script allowing the Slide Show:
<script type="text/javascript">
jQuery(document).ready(function($){
$("#photo-rotator").tabs({fx:{opacity: "toggle"}}).tabs("rotate", 6000);
});
</script>
Update: I've just tried:
<script>
$("#slide-1").swiperight(function() {
$.mobile.changePage("#slide-2");
});
</script>
With no such luck ~
ANY SUGGESTIONS - ?
To expand on my comment, here is how to programatically change a tab with jQuery UI's tab widget:
//cache all the tabs (I called them slides...)
//get the number of tabs
var $slides = $('div[id^="slide"]')
slideCount = $slides.length;
//bind the event handlers necessary
$slides.bind('swipeleft', function () {
//this is to go to the next index
//get current slide index and figure out the next one
var currentIndex = $(this).index();
if ((currentIndex + 1) < slideCount) {
currentIndex++;
} else {
//the end was reached, so go back to the first tab
currentIndex = 0;
}
//now select the new tab
$("#photo-rotator").tabs( "select" , currentIndex);
}).bind('swiperight', function () {
//this is to go to the previous index
//get current slide index and figure out the previous one
var currentIndex = $(this).index();
if ((currentIndex - 1) >= 0) {
currentIndex--;
} else {
//the beginning was reached, so go to the last tab
currentIndex = slideCount;
}
//now select the new tab
$("#photo-rotator").tabs( "select" , currentIndex);
});

Categories

Resources