javascript foreach loop values - javascript

I am new to this and I am struggling with one thing for such a long time...
I use foreach loop to show all images in a list, that works fine.
<?php
foreach($listImages as $image) {
?>
<a href="#" class="show_hide" title="<?php echo $image; ?>" >
<img src="foto.php?file=<?php echo $image; ?>" alt="building thumb"/>
</a>
<?php
}
Then I use simple show and hide script that looks like this:
<script type="text/javascript">
$(document).ready(function(){
$(".slidingDiv").hide();
$(".show_hide").show();
$('.show_hide').click(function(){
$(".slidingDiv").slideToggle();
});
});
</script>
Finally, when I use div slidingDiv, it works as I expect, but I also need to know name of the image I clicked on but I really don't know how to do that.
<div class="slidingDiv">
!!! I need to know $image from the foreach loop here !!!
</div>
Thank you for your help!

Related

JS Display none with PHP foreach only working with first elemnt

I'm bringing articles from a database with ORDER BY RAND() with a PHP foreach cycle:
<?php foreach($posts as $post): ?>
<div class="post" id="post">
<article>
<div class="post-head">
<a href="<?php echo ROUTE; ?>/profile.php/<?php echo $post['user_id']; ?>">
<img class="post-pfp" src="<?php echo ROUTE; ?>/users_pics/<?php echo ($post['profile_pic']); ?>">
</a>
<h1>
<a class="links-3" href="<?php echo ROUTE; ?>/profile.php?user=<?php echo $post['user_id']; ?>"><?php echo $post['post_by']; ?></a>
</h1>
<p class="post-date"><?php echo get_date($post['date']); ?></p>
<div class="x_hover" onclick="hide_post()">
<img src="<?php echo ROUTE; ?>/icons/cross.svg">
</div>
<hr id="post-hr">
<br>
<a href="<?php echo ROUTE; ?>/post.php?p=<?php echo $post['ID']; ?>">
<p class="post-content"><?php echo $post['content']; ?></p>
</a>
</div>
</article>
</div>
<?php endforeach; ?>
As you can see, the div with the class x_hover has an onclick attribute:
<div class="x_hover" onclick="hide_post()">
<img src="<?php echo ROUTE; ?>/icons/cross.svg">
</div>
What the hide_post() function does is this:
var post = document.getElementsByClassName("post");
function hide_post(){
if (post[0].style.display = "block") {
post[0].style.display = "none"
}
}
I'm new to JS so I have some issues as well.
We are declaring that var post is equal to all the elements with the class name "post", such as the HTML code I added at the beginning, has the class post:
<div class="post" id="post">
This div has the display: block; attribute. However, when I run all this code, It only turns into display: none the first element that brings us from the database, it doesn't works with the rest of them...
Why is this happening?
IDs must be unique and since you have named all of the post only the first one will ever been "seen". Make the IDs unique, change your hide_post function to accept a ID name to hide, and add the unique ID to your onclick calls.
Change
<div class="post" id="post">
to something like
<div class="post" id="post<?php echo $post['ID']; ?>">
Then change
<div class="x_hover" onclick="hide_post()">
to
<div class="x_hover" onclick="hide_post('post<?php echo $post['ID']; ?>')">
Finally, modify your hide_post function to accept the name of the ID to show or hide.
function hide_post(idToHide){
if (idToHide.style.display = "block") {
idToHide.style.display = "none"
}
}
When you use getElementsByClassName it returns an HTMLCollection. You should iterate elements and hide all of them if it's what you intent to. Right now you are just hiding 0th element of this collection.
var posts = document.getElementsByClassName("post");
for (let post of posts) {
if (post.style.display = "block") {
post.style.display = "none"
}
}
If you intent to hide a single post you give unique ids to divs, and call hide_post with id of that post. Also you should use getElementById for that. Notice that it's not plural. Function should be like this:
function hide_post(postId){
var post = document.getElementById(postId);
if (post.style.display = "block") {
post.style.display = "none"
}
}
A more cleaner way of doing this would be.
function hide_post() {
document.querySelectorAll('.post').forEach(v => {
if(v.style.display == block) v.style.display = none; }); }

Pass the value when a <div> has onclick function and the data inside is changing dynamically

enter image description hereThis is my index_category.php.
<?php
include("db.php");
$sql="SELECT * from tcategory";
$conect= mysqli_query($conn, $sql) or die ("Failed To Connect.");
while($rows= mysqli_fetch_array($conect, MYSQLI_ASSOC)){ ?>
<div class="dialog-outer" data="<?php echo $rows['cat_id']; ?>" onclick="openNav()">
<div class="dialog-inner">
<?php echo $rows['cat_nm'];?>
</div>
</div>
<?php }
?>
This is the side nav to which I want to pass the data of div
<div id="mySidenav" class="sidenav">
<h3 class="sub"><i class="fa fa-arrow-right" aria-hidden="true"></i><strong> Sub Category</strong></h3>
×
<div id="result">
<?php include("functions/sub_category.php")?>
</div>
</div>
<script>
function openNav() {
$("#mySidenav").attr("style","width:250px");
var id=$(".dialog-outer").attr("data");
alert(id);
$.post('functions/sub_category.php',{id: id},function(data){
$('#result').html(data);
});
}
function closeNav() {
$("#mySidenav").attr("style","width:0px");
}
</script>
The problem is it is taking data=1 only but in network it showing as data=1 data=2 data=3 so on...
How to pass all the values from div in index_category.php to script in index.php
as u can see in the image i want to filter the sub category based on category. But when i click on any of the category it is taking only first value.But when u look in the image(inspect element) it is taking all the values as data=1 data=2 so on...when i click on category i want to get their respective id's.
If I understand correctly your your outer nav is repeated, that means that your $(".outer-nav") will return an array of elements not just one. You will need to iterate over them to read their data attributes. If you are looking to get just one specific one I would recommend using JQuery(since you are using it) selector for the click detection and from there working out the .outer-nav that you need.
Sorry if I did not understand your question correctly, but you use a weird mixture of pure JS and JQuery so it is a bit stange to read the code.
as #Aurus told, it is not only one element. You should modify like this:
===== 1st method =====
.... onclick="openNav(this)">
and the function too:
function openNav(element) {
...
var id=$(element).attr("data");
.....
}
===== 2nd method =====
<div class="dialog-outer" data="<?php echo $rows['cat_id']; ?>" onclick="openNav('oid_<?php echo $rows['cat_id']; ?>')" id="oid_<?php echo $rows['cat_id']; ?>">
and the function too:
function openNav(id) {
...
var id=$("#"+id).attr("data");
.....
}

How to insert PHP snip into a Javascript script

The variable in $pieces[12] is the url of an image on my server, some times when the page loads there is a broken image. My script is suppose to find the broken image error if there is one and replace it with $pieces[12] again. If that sounds right. But I don't know how to do it with my code.
<div class="right_ad" id="right_ad">
<script>
<img src="<?php echo $pieces[12]; ?>"
onError="this.onerror=null;this.src='<?php echo $pieces[12]; ?>';"
style="width: 100%;max-height: 100%"/>
</script>
</div>
You should urlencode those values. My tip is that there are special values in your filenames.
function onError_run_this_func(){
//get your new image url with ajax function
//or if you already have it in $pieces[12] then use it.
$.('.image-class).attr('src', '<?php echo $pieces[12]; ?>');
}
<div class="right_ad" id="right_ad"><script><img class="image-class" src="`<?php echo $pieces[12]; ?>" onError="onError_run_this_func()" style="width: 100%;max-height: 100%"/></script> </div>`

Dynamical Image loaded from php after javascript need to run

I have page with image loading Dynamical from php.The image height is
various px size(70,130,100,60).my need is how can get the image size currently viewed in page automatically in alertbox i try same code is not working.please help
code
<?php
foreach ($images as $image) {
?>
<img src="<?php echo $image['url']; ?>" class="img_test" id="<?php echo $image['url']; ?>" width="70" style="max-height:70px" onclick="imagesize(this)" />
<?php
}?>
<script>
$( window ).load(function() {
$( ".img_test" ).each(function( index ) {
alert('Height: '+$(this).height());
});
});
function imagesize(obj){
alert($(obj).height());
}
</script>
if we click the image the height will display.in page load after automatically can't be display
It's important to understand that it's navigator (client) which load image and PHP is running into your server and send text to client.
Use a listener .on to get event 'click'.
Moreover, use $(document).ready and not .load to wait that images are loading
<?php foreach ($images as $image) { ?>
<img src="<?php echo $image['url']; ?>" class="img_test" id="<?php echo $image['url']; ?>" width="70" style="max-height:70px" />
<?php } ?>
$(document).ready(function(){
$( ".img_test" ).each(function(){
alert('Height: '+$(this).height());
});
$(".img_test").on("click", function(){
alert($(this).height());
});
});
http://jsfiddle.net/3c9CN/

Need help making jQuery loop for basic .fadeIn()/.fadeOut() slider

I'm new to jQuery and am having trouble figuring out the right way to loop a set of code for a basic carousel/banner rotator. I've tried a few versions of "for" statements and .each(), but I can't get it to work on my own so I'm reaching out for help.
Here's my code so far:
$('.next-1').click(function () {
$('.featured-1').fadeOut(500,function(){
$('.featured-2').fadeIn(500,function(){
$('.featured-2').toggleClass("hide");
});
});
});
$('.next-2').click(function () {
$('.featured-2').fadeOut(500,function(){
$('.featured-3').fadeIn(500,function(){
$('.featured-3').toggleClass("hide");
});
});
});
And then a similar code block for going back within the slider:
$('.prev-2').click(function () {
$('.featured-2').fadeOut(500,function(){
$('.featured-1').fadeIn(500,function(){
$('.featured-2').toggleClass("hide");
});
});
});
$('.prev-3').click(function () {
$('.featured-3').fadeOut(500,function(){
$('.featured-2').fadeIn(500,function(){
$('.featured-3').toggleClass("hide");
});
});
});
This code does work right now, I just don't want to have to output so many unnecessary lines of code when I know I could loop it. I'd like to be able to loop until there are no more "featured-n" divs to cycle through (being able to cycle around to the beginning would be great too!)
Here's the PHP/HTML I'm using to generate each "featured-n" div block:
function home_slider_loop() {
$count = 0;
query_posts ('tag=slider');
if (have_posts()) : while (have_posts()) : the_post();
$count++;
?>
<div class="featured-post featured-<?php echo $count; if ($count>1) { echo ' hide';}?>">
<div class="featured-header">
<h1 class="featured-title"><?php the_title(); ?></h1>
<p class="author">Written by Evan Luzi</p>
</div>
<div class="image-wrap">
<?php the_post_thumbnail('full', array('class' => 'slider-image')); ?>
<div class="slider-nav">
<div class="featured-prev prev-<?php echo $count; ?>"></div>
<div class="featured-next next-<?php echo $count; ?>"></div>
</div><!--End Navigation-->
</div><!--End Image <?php echo $count; ?>-->
<div class="featured-footer">
<?php the_excerpt(); ?>
<a class="more-link" href="<?php the_permalink(); ?>" alt="<?php the_title(); ?>" >Read more</a>
</div>
</div><!--End Featured <?php echo $count; ?>-->
<?php
endwhile;
endif;
}
Here's a sample of one of the static HTML outputs (just imagine this iterated several times with the "featured-n" classes incrementing:
<div class="featured-1">
<div class="featured-header">
<h1 class="featured-title">5 Useful Cinematography Apps for iOS You Should Download Today</h1>
<p class="author">Written by Evan Luzi</p>
</div>
<div class="image-wrap">
<img width="1018" height="416" src="http://www.tbabdev.com/wp-content/uploads/2013/07/cinematography-apps-8-hero.jpg" class="slider-image wp-post-image" alt="cinematography-apps-8-hero" />
<div class="slider-nav">
<div class="featured-prev prev-1"></div>
<div class="featured-next next-1"></div>
</div><!--End Navigation-->
</div><!--End Image 1-->
<div class="featured-footer">
<p>The devices we have in our pockets, the ones that can run these apps, these are the new leathermans. They have everything we need. They eliminate the need to carry paper manuals and enable us to do complex timelapse calculations in a fraction of the time as a paper and pen.</p>
<a class="more-link" href="http://www.tbabdev.com/?p=27" alt="5 Useful Cinematography Apps for iOS You Should Download Today" >Read more</a>
</div>
</div><!--End Featured 1-->
You can see the code in action at http://www.tbabdev.com/
Thank you in advance for your help and please be kind to a n00b :)
Use something like this :
$('.nav .prev').click(function(){
activeBlock = $('.featured.active');
prevBlock = activeBlock.prev('.featured');
activeBlock.fadeOut('slow',function(){
prevBlock.fadeIn().addClass('active');
}).removeClass('active');
});
$('.nav .next').click(function(){
activeBlock = $('.featured.active');
nextBlock = activeBlock.next('.featured');
activeBlock.fadeOut('slow',function(){
nextBlock.fadeIn().addClass('active');
}).removeClass('active');
});
Html
<div class="nav">
<div class="prev"> </div>
<div class="next"> </div>
</div>
<div class="featured-post featured <?php if($count>1) echo 'hide' ?>">
<div class="featured-header">
<h1 class="featured-title"><?php the_title(); ?></h1>
<p class="author">Written by Evan Luzi</p>
</div>
<div class="image-wrap">
<?php the_post_thumbnail('full', array('class' => 'slider-image')); ?>
</div>
<!--End Image <?php echo $count; ?>-->
<div class="featured-footer">
<?php the_excerpt(); ?>
<a class="more-link" href="<?php the_permalink(); ?>" alt="<?php the_title(); ?>" >Read more</a>
</div>
</div>
You could do it this way :
$('.featured-next, .featured-prev').click(function () {
//find out if the clicked element is a prev or next element, extract the last part, will be useful later
var direction = $(this).hasClass("featured-next") ? "next" : "prev";
//select the ".featured-n" block which is the super-parent of clicked element
var $fullBlock = $(this).closest('div[class^="featured-"]'); //or add a class here to make your life easier
//fade out full block
$fullBlock.fadeOut(500, function () {
//search for the next element and show it
//note that $fullBlock.next() => $fullBlock["next"]() => $fullBlock[direction]()
$fullBlock[direction]().fadeIn(500, function () {
//toggle the class "hide" of the element next to fullBlock
$(this).toggleClass("hide");
});
});
});
Explanation:
You can join up both prev and next events together.
Then, you have to check if its a next or a prev element. Set that to a variable called direction. We'll be using this to find out if we have to use prev() or next() when we're trying to fadeIn featured-n divs.
Find the parent with the class set to featured-n (in your case its the superparent). It might be better if you give a common class to all these elements so that we can stop using 'div[class^="featured-"]' selector, which is slightly inefficient.
Fade out the superparent.
In the callback, based on the direction variable, we'll have to decide if the carousel is gonna go to prev block or next block, something like this :
if(direction === "prev")
{
$fullBlock.prev().fadeIn(//your code)
}
else
{
$fullBlock.next().fadeIn(//your code)
}
You must also know that, in an object like this :
var data = {"name" : "Blah Blah"}
To get the "Blah Blah" out, we can say
data.name
or we could say :
data["name"]
So based on this, in our situation, instead of
$fullBlock.prev()
Or we could say
$fullBlock["prev"]()
Which is what direction variable contains. So finally, we could do this to select the next/prev element based on what was clicked :
$fullBlockdirection
Show the prev/next element.
Add/remove "hide" class.
Hope this helped!

Categories