I'm trying to generate random div widths for each database result that's output.
The code works when it's outside the loop, but every div is the same 'random' width.
load page and all divs are 200px
refresh page and all divs are 150px
refresh page and all divs are 250px ...etc.
The trouble being, I need each individual div to be a random width, not all the same random width... for that reason I've added my javascript inside the loop in order to get a new 'random' width each time a database value is output.
And of course, it's not working!
<?php
$result = mysql_query("SELECT * from tbl_status ORDER BY tbl_status.date desc");
while($row = mysql_fetch_array($result))
{
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
var x = Math.floor((Math.random()*150)+150);
$('.statusCont').width(x+'px');
});
</script>
echo'
<div class="statusCont">
<div class="statusUsr">Tom Adams - Newcastle</div>
<div class="statusTxt"><p>' . $row['status'] . '</p></div>
</div><!-- ends .statusCont -->
';}
?>
The reason that all the div's have the same random width is because the jquery class selector $('.statusCont') will return all elements with that class. So when your loop prints out the last selector it applies to all of the previous loaded elements.
Instead of including the javascript in the php while loop you can just write a script in the head that will affect the page after it's loaded
$(document).ready(function () {
$('.statusCont').each(function () {
var x = Math.floor((Math.random() * 150) + 150);
$(this).width(x);
});
);
Related
I'm using a JS function in Wordpress with Ajax that loads content of a post in a modal div when certain elements are clicked. The JS function looks like this:
function openProjectModal($that) {
var post_id = $that.attr("rel");
window.location.hash = $that.data("slug");
$("#content-projects").load(localization.ajax_url+"?action=load_more_post&pid="+post_id,{},function(data,status){
initImageLoad();
});
}
The function that creates the markup in functions.php looks like this:
function load_more_post_callback() {
if( isset($_GET["pid"]) ){
$post = get_post( $_GET["pid"] );
if( $post instanceof WP_Post ) {
echo '<div id="close"></div>';
echo '<section id="title-projects"><h1>' . get_the_title($post->ID) . '</h1><p class="project-meta">' . get_field("location", $post->ID) . ' (' . get_field("year", $post->ID) . ')</p></section>';
} else {
// nothing found with the post id
}
} else {
// no post id
}
wp_die();
}
The h1 in the new content has a font applied to it through CSS that isn't used on the initial page. So when the div gets loaded with the content from the Ajax call, there is a delay in the loading of the font, which looks weird. It goes from blank, to Times New Roman, to the right font. When I close the modal and open a new one, the font is instantly loaded like it should be. I guess that it gets cached from the first load.
I've added the fonts in the CSS that is being used on the whole site, but it seems like the browser only loads the fonts that are actually being used in the markup, since this font that is unique for the Ajax content gets loaded when the Ajax content gets loaded.
I've only noticed this in Safari though, but it would be nice if there was a workaround for this even if it's just a special issue in Safari. Any ideas on how to preload the font before it's shown?
In your modal simply do
<h2 class="myTitleFont">Title</h2>
Then in css you can do:
.myTitleFont {
font-family. "yourFont";
}
or if really you have to:
.myTitleFont {
font-family: "yourFont" !important;
}
Obviously "yourFont" is the name of your font.
I still believe is just a css issue, however, create a callback for your modal when it is opened and run:
$(".modal").on.("show", function(){
addGoogleFont();
});
function addGoogleFont() {
$("head").append("<link href='https://fonts.googleapis.com/css?family=" + FontName + "' rel='stylesheet' type='text/css'>");
$(".modal h2").css("opacity", "1");
}
And set your modal h2 to opacity 0 so you won't see it until
.modal h2 {
opacity: 0;
}
i have multiple dynamic div ids in a while loop, this div id is to be used in JavaScript to display a radial progress bar. my problem is that although i have unique ids i cant pass this unique ids to my JavaScript to show the different radial progress for each. i have tried using div class but that just repeats the last id of the loop in all progress bars. i don't want to use links or hovers to get the unique id as i want the JavaScript to fire on page load. How can i make each div in my while loop display the progress the progress bar correctly.
sample.php
<?php
..................................
while($obj = $getcDetails->fetch()){
//div that displays radial progress bar
echo '
<div class="page" style="color:#000000;">
<div id="progress-pie-chart'.$Id.'" data-percent="'.$cId.'">
<div class="ppc-progress">
<div class="ppc-progress-fill"></div>
</div>
<div class="ppc-percents">
<div class="pcc-percents-wrapper">
<span>%</span>
</div>
</div></div></div>';
?>
sample.js
<script>
$(function(){
var $ppc = $('.progress-pie-chart'),//add dynamic id here to display multiple progress bar unique to that div
percent = parseInt($ppc.data('percent')),
deg = 360*percent/100;
if (percent > 50) {
$ppc.addClass('gt-50');
}
$('.ppc-progress-fill').css('transform','rotate('+ deg +'deg)');
$('.ppc-percents span').html(percent+'%');
});
</script>
Any help or guide is greatly appreciated.
You can base this logic off of just a class. Given that the progress fill and percents are children of the progress-pie-chart, you can find the ones you need to change, with a contextual lookup.
$(function(){
$('.progress-pie-chart').each(function(){
var $ppc = $(this)
, percent = parseInt($ppc.data('percent'))
, deg = 360*percent/100;
if (percent > 50) {
$ppc.addClass('gt-50');
}
$ppc.find('.ppc-progress-fill').css('transform','rotate('+ deg +'deg)');
$ppc.find('.ppc-percents span').html(percent+'%');
});
});
What I'm trying to do is run a jQuery function that converts a number score into a bar rating system using the score as a percentage to set the width of the bar. The divs and the scores inside of the divs are being generated dynamically from XML with XSL.
The problem is that the function is taking the score from the first DIV and applying it to all subsequent DIVs instead of taking the score from each DIV separately. For reference, .Product_Rating_Score_Overall is the score, .ratingBar is the grey background behind my score bar, .ratingOverall is the green bar that has its width adjusted to reflect the score percentage. Here is an image of my rating system(as you can see the rating of 2.0 from the first DIV is being transferred to the other DIVs. The ratings for the other DIVs should be as follows 7.0 6.0, 6.0, 6.0 - these are just dummy scores for now):
Here is my html code:
<div id="F26_ResultsDiv" style="display:none">
<div class="items"><div class="ColOne">
<div class="item">
<div class="otherStuff">
<span>Kindermat Basic Red/Blue</span>
<div class="overall"><span><span class="content">
<ul>
<li class="Product_Rating_Score_Overall">2.00</li>
</ul>
</span></span>
<div class="ratingBar">
<div class="ratingOverall">
</div></div></div></div></div>
Here is my jQuery code:
$('.overall').each( function() {
var score = parseFloat($('.Product_Rating_Score_Overall').text()).toFixed(1);
console.log(score);
var scorePerc = score * 10;
$('.ratingOverall').width(scorePerc + '%');
$('.Product_Rating_Score_Overall').text(score);
});
Any help is really appreciated. Thanks so much.
You need to localize your selector:
$('.overall').each( function() {
var score = parseFloat($(this).find('.Product_Rating_Score_Overall').text()).toFixed(1);
console.log(score);
var scorePerc = score * 10;
$(this).find('.ratingOverall').width(scorePerc + '%');
$(this).find('.Product_Rating_Score_Overall').text(score);
});
Update: added fiddle https://jsfiddle.net/mbho2bjj/5/
Using $(this) and find() function.
for each element with class overall you find under it the element with class Product_Rating_Score_Overall
$('.overall').each( function() {
var score = parseFloat($(this).find('.Product_Rating_Score_Overall').text()).toFixed(1);
console.log(score);
var scorePerc = score * 10;
$(this).find('.ratingOverall').width(scorePerc + '%');
$(this).find('.Product_Rating_Score_Overall').text(score);
});
The problem is with your second line and the other references being global and not localized properly. You should be changing it to grab the local value, not the first one each time that appears on the global scope, which is why you are getting the functionality you see now. Right now you think its not working but it is working exactly as it was written. By adjusting the code to act on the local variables inside each '.overall' we will get the proper results that you are looking for.
Try changing that code like this:
$('.overall').each( function() {
var score = parseFloat($(this).find('.Product_Rating_Score_Overall').text()).toFixed(1);
console.log(score);
var scorePerc = score * 10;
$(this).find('.ratingOverall').width(scorePerc + '%');
$(this).find('.Product_Rating_Score_Overall').text(score);
});
i made this hover menu but is buggy
this my jquery code
$("#right_side li").mouseenter(function(e) {
$(this).children('ul').stop(true,true).slideDown();
});
$(this).stop();
$("#right_side li").mouseleave(function(e) {
$(this).children('ul').stop(true,true).slideUp();
});
and this my php code
function menu($li)
{
echo "<ul class='hovermenu'>";
$result = mysqli_query($li, "SELECT * FROM `categories` WHERE 1") or die(mysqli_error($li));
while ($Row = mysqli_fetch_array($result)) {
echo "<li class='cat'><div class='cat_div' ><a href='index.php?cat=".$Row['catid']."'>" . $Row['catname'] . "</a></div><ul class='sub'>";
$result2 = mysqli_query($li, "SELECT * FROM `brand` WHERE catid=".$Row['catid']."") or die(mysqli_error($li));
while ($Row2 = mysqli_fetch_array($result2)) {
echo "<li><a href='index.php?brand=".$Row2['id']."&cat=".$Row['catid']."'>" . $Row2['name'] . "</a></li>";
}
echo"</ul></li>";
}
echo "</ul>";
}
my problem is
when my mouseleave
and i mousein too fast
my menu sliding up and down too fast
please help meeeee!!!
Add the speed to your slideUp call e.g. "slow"
slideUp("slow")
You can also use a value in milliseconds.
you may simply add a time in milliseconds like slideUp(1000) or slideDown(300) or slideDown("fast") or slideUp("slow")
Hope this helps.
Can you change your script to this one and let me know if the issue is fixed
$("#right_side li").on({
mouseenter: function(){
$(this).children('ul').stop().slideDown();
},
mouseleave: function(){
$(this).children('ul').stop().slideUp();
}
});
There is a known issue with the jQuery slideUp/slideDown functions when the element being slid up/down has no set height. Ensure the element to be hidden has a specified height.
ALSO, the min-height css property will mess things up. Remove min-height from the element.
Reference:
https://forum.jquery.com/topic/slideup-slow-and-slidedown-slow-happening-instantly
I can't get the actually LazyLoad plugin to work for me so I am trying to write my own with. Currently I have a list of images loading inside of a DIV. They are pulled by a PHP query to the mysql database. The DIV scroll is set to auto. The code I am using is:
<div id="b1" style="overflow:auto;">
<?PHP $result = mysql_query("SELECT * FROM images");
while($row = mysql_fetch_assoc($result)) {
echo "<img src='$row[photo]' style='display:none'> <br>";
}
</div>
<script type="text/javascript">
function imgCheck() {
var position = $("img").offset().top;
var scrollCheck = $("#b1").scrollTop() + $("#b1").height();
if ( scrollCheck > position) {
$("img").fadeIn("fast");
}
$("#b1").scroll( function() { imgCheck() } );
</script>
Although this is not quite working for me. Could anyone help me out or shoot out some suggestions?
A couple of things:
As the others have already said, your code has syntax errors - both with the PHP and the Javascript.
If you use display: none, the elements will not take up any height, thus causing the entire thing to become unscrollable and fail.
The first few elements should be visible without the user having to start scrolling
Taking these into consideration, we can try writing this this way:
// Cache the containing element and it's height
var b1 = $('#b1'),
h = b1.height();
// Insert 20 img's - simulating server-side code
for(var i = 0; i < 20; i++){
$('<img />', {
src: 'http://placehold.it/100x100',
alt: '',
class: 'hidden',
width: 100,
height: 100
// visibility: hidden to retain it's size
}).css('visibility', 'hidden').appendTo(b1);
}
b1.scroll(function(){
// Loop through only hidden images
$('img.hidden').each(function(){
// $(this).position().top calculates the offset to the parent
// So scrolling is already taken care of here
if(h > $(this).position().top){
// Remove class, set visibility back to visible,
// then hide and fade in image
$(this).css('visibility', 'visible')
.hide()
.removeClass('hidden')
.fadeIn(300);
} else {
// No need to check the rest - everything below this image
// will always evaluate to false - so we exit out of the each loop
return false;
}
});
// Trigger once to show the first few images
}).trigger('scroll');
See a demo of this here: http://jsfiddle.net/yijiang/eXSXm/2
If all of the images are hidden, then there will never be a 'scroll' even called as the element will never scroll.
What exactly are you trying to achieve? If it is to have new images that weren't previously visible, but now may be, become visible then you will have to do something like;
<div id="b1" style="overflow:auto;">
<?php $result = mysql_query("SELECT * FROM images");
while($row = mysql_fetch_assoc($result)) {
echo "<img src='$row[photo]' style='visibility:hidden'> <br>";
} ?>
</div>
<script type="text/javascript">
function imgCheck() {
var scrollCheck = $("#b1").scrollTop() + $("#b1").height();
$("#b1 img").each(function() {
var position = $(this).offset().top;
if (scrollCheck > position) {
$(this).fadeIn("fast");
}
});
}
$(document).ready(imgCheck);
$("#b1").scroll(imgCheck);
</script>
Note that I haven't tested the above, and I can imagine that it will result in all images being shown immediately, since all of their 'top's will be 0 due to them all being hidden and not having their position effected by previous images in the DOM.
Edit
I've changed the code above so the img's have visibility:hidden, which should give them a height and take up space in the DOM
I've been testing it, it seems to work with some modifications:
http://jsfiddle.net/antiflu/zEHtu/
Some things I had to change:
I added the closing } for the imgCheck() function, you forgot it
Some items need to be visible from the beginning on, otherwise the scrollbar never appears and imgCheck() is never called.
OK the problem with the above was that the images don't fade in separately upon scroll. I got it to work though with some modifications:
http://jsfiddle.net/antiflu/GdzmQ/
What I changed:
I changed the display: none to opacity: 0 so that any invisible picture has at least an empty placeholder of the same size, so that the scroll bar will be visible.
I then fade in using animate to opacity: 1
I used jQuery each() to iterate over the images and check for each of them if they should or should not be faded in (instead of checking for all, like before).
I wrapped the images in DIV's. I don't think it's necessary, but it doesn't harm either.
I tagged each image with an id, so that I can single them out for the fadein.
There are still some esthetic issues but this should help you on your way.