How to do for each div its own trigger - php

for example i have:
<?php foreach($query as $q): ?>
<div class="item">
<?php echo img($q->images); ?>
</div>
<?php endforeach; ?>
so this code renders 5 divs in a line, each line 5 divs, and this code:
<?php foreach($url->result() as $u): ?>
<script>
$(document).ready(function(){
$('div.item').click(function(){
setTimeout(function(){
window.open('<?php echo $u->url; ?>');
}, 500)
})
})
</script>
<?php break; ?>
<?php endforeach; ?>
doesn't matter what div we click, it will open a new window with the same url, but what if I have 5 different urls in my database, and I want that when we click the first div of each line it open one window with the first url and when we click the second it will open the second url
i thinked that this is possible by using classes, for example class="item1", item2, item3, item4, item5, but what if we have only 3 urls, not 5, in this case how can i make that the first three divs will open the first 3 urls, but the 2 left, will open the last, it is the 3 div
sorry for my poor english, maybe you have an idea of how to do this, thanks!
ps: i am using codeigniter

Instead of a class you can have id like item_1, item_2 etc. for each of the division and in javascript you can setup listeners in each of the divs separately.
<?php $index = 0;?>
<?php foreach($query as $q): ?>
<div id="item_<?php echo $index++;?>">
<?php echo img($q->images); ?>
</div>
<?php endforeach; ?>
For Javascript the code goes as:
<?php $index = 0;?>
<?php foreach($url->result() as $u): ?>
<script>
$(document).ready(function(){
$('#item_<?php echo $index++;?>').click(function(){
setTimeout(function(){
window.open('<?php echo $u->url; ?>');
}, 500)
})
})
</script>
<?php break; ?>
<?php endforeach; ?>

2 options i can think of. first is to add the url as a data attribute of the div so data-url="url here" then you can just use $(this).attr('data-url') to get the link in the javascript action (may even be able to use data() but not sure on IE compatibility).
Second option would be to have a hidden anchor in the div, then in the javascript action you can just select the anchor within the clicked div to get the URL

Related

How to fix a jQuery code looping incorrectly in a PHP foreach loop

I'm trying to loop a piece of jQuery code inside a foreach loop. Each article in the loop have a phone number custom post type related (ACF). At this point the loop works well.
As you see, the jQuery code only replace an image to another while user clicks in order to show the number (Ex : "Display Phone Number" image, becomes "555-555-1234").
The problem is that when I click in any image to display number...all articles show their phone number at the same time. I think is an ID problem in my jQuery code. After two days of searching and testing different codes this problem still not resolved yet.
Any suggestions/tracks will be very welcome !
Thanks
====
Things I have tried :
I have tried to put the jQuery code outside the foreach (same result)
I have tried to change the id image into a class (works better)
I have tried different jQuery functions (replaceWith(), show(), etc)
foreach ($related_posts_articles as $related_post ){
<div class="col-sm-6 col-md-6 col-lg-3 col-xs-12">
<div>
<a href="<?php echo get_permalink($related_post->ID); ?> ">
<?php echo get_the_post_thumbnail($related_post->ID,"square-300",array('class' => 'img-responsive')); ?>
</a>
<div>
<a href="<?php echo get_permalink($related_post->ID); ?>">
<h2>
<?php echo wp_html_excerpt(strip_tags(get_field('acf_titre_mini', $related_post->ID)), 30, '...' ); ?>
</h2>
</a>
<div>
<?php echo wp_html_excerpt( strip_tags(get_field('acf_description_mini',$related_post->ID)), 129, '...' ); ?>
</div>
<!-- START bloc number -->
<?php if( get_field('acf_numero_image', $related_post->ID) ): ?>
<div>
<img class="input_img" src="<?php the_field('acf_btnVoirNum_image', $related_post->ID); ?>" >
<script>
jQuery(document).ready(function($) {
$( ".input_img" ).click(function() {
$( ".input_img" ).attr( "src", "<?php the_field('acf_numero_image', $related_post->ID); ?>" );
});
});
</script>
</div>
<?php endif; ?>
<!-- END bloc number -->
</div>
</div>
</div>
}
Take note of the 'this' Context
When an event fires in jquery the callback function this context is set to the element which the event was fired from.
jQuery(document).ready(function($) {
$(".input_img").click(function() {
// Use `this` to target the event element
$(this).attr("src", "<?php the_field('acf_numero_image', $related_post->ID); ?>" );
});
});
Advice:
You shouldn't generate same jquery code inside each iteration of the for each. Since you're repeating unnecessary code. You can harness HTML data-* attributes to achieve the outcome you seek.
You are giving the class name the same for all images. Also by looping you are adding lot's of scripts. You can add Onclick events to image and create a function and grab the data and do you things. Also, you can add extra attributes to img tag to get your data. Also try to put different ID like below,
foreach ($related_posts_articles as $key=>$related_post ){
<img id="img-<?php echo $key; ?>" onclick="myFunction(this)" class="input_img" src="<?php the_field('acf_btnVoirNum_image', $related_post->ID); ?>" >
}

Php generating divs, then hiding all the divs

Everything works except for the hide portion. I'm simply trying to hide each div as it is being generated, and I need to get control of the divs as well. So I'm guessing that the div id part is very wrong when I'm trying to increment. Please help!
<?php
$counter=0;
foreach ($foo as $key => $value){
$counter++;
?>
<div id="ad<?php $counter;?>">
<?php include("showPage.php");?>
</div>
<script>$("#ad<?php $counter;?>").hide();</script>
<?php
}
?>
Second part of question:
<script>
$(document).ready(function(){
$("#FooButton").click(function(){
if($('div#ad1').is(':visible')){
$("div#ad1").hide();
$("div#ad2").show();
}
});
});
</script>
Yes you need to echo the value like this
echo $counter;
You need to echo out the value of $counter.
Here:
<div id="ad<?php echo $counter;?>">
<?php include("showPage.php");?>
</div>
<script>
$(document).ready(function(){
$("#ad<?php echo $counter;?>").hide();
});
</script>
Update:
After looking at the above solution, I cannot recommend you calling $(document).ready() in a loop. A more efficient solution to this would be to add style display: none to the generated div and not use the javascript here, like follows:
<div id="ad<?php echo $counter;?>" style="display:none;">
<?php include("showPage.php");?>
</div>

How to link to a specific part in the same page with jquery and php?

I know to link to a part in the same page like :
<a href='#A'>A</a>
<a name='A'>Here is A</a>
But when I designed it with jquery and php, ı have a problem. My design is like :
There are all letters of alphabet. Under the letters, there are there are divs (item_A,item_B,item_c etc...). When the user click K letter for example, page will link to #K div and also #K div display its content.(Because when the site open first, item divs' display are none). But the problem is, although #K (K is just example) K is displayed its content, page did not redirect to #K div. You must scroll by yourself.
Here is the code :
<div class="content_letters">
<ul>
<?php $array_letter = array("A","B","C","Ç","D","E","F","G","H","I","İ",
"J","K","L","M","N","O","P","R","S","Ş","T",
"U","Ü","V","Y","Z");
for ($i=0;$i<27;$i++) {
echo "<li><a id='letter_{$array_letter[$i]}'
href='#letter_{$array_letter[$i]}'>{$array_letter[$i]} | </a></li>";
}
?>
</ul>
</div>
<?php
for ($i=0;$i<27;$i++) {
?>
<div class="content_letter_block">
<div class="text">
<div class="show_hide">
<a class="button" id="
<?php echo 'button_letter_'.$array_letter[$i]; ?>">SHOW/HIDE</a>
</div>
<a name="<?php echo "letter_".$array_letter[$i].'">';?>
<?php echo $array_letter[$i]; ?></a> starts from here</div>
</div>
</div>
<?php } ?>
<div style='display:none' id='<?php echo "item_".$array_letter[$i];?>'>
Here is item...
</div>
Here is the jquery code :
$(document).ready(function() {
// target everything with IDs that start with 'button_letter'
$("[id^='button_letter']").click(function () {
// split the letter out of the ID
// of the clicked element and use it to target
// the correct div
$("#item_" + this.id.split("_")[1]).toggle();
});
$("[id^='letter']").click(function () {
$("#item_" + this.id.split("_")[1]).show();
});
});
Don't have the time to see all your code, but can't use a scrollTop() method ?
See here.
To scroll with jQuery to a specific ID in your page, use
$('html,body').animate({scrollTop: $("#"+id).offset().top},'slow');
You can specify an anchor in your url as well.
<a href="your-page.html#k" />
When you click the link you will be taken to that page and the document will scroll automatically to the position of <a name="k">

append display:none to subsequent li on loop

We have a slider, we want to use. Dead simple stuff. But I need it to become a little more dynamic.
We have a blog roll, which runs and displays on a php loop, basically.. if we set the loop to 6.. it generates 6 sets of divs.
Now my thought is, put the DIV which displays the blog post within a slider, then we can display subsequent posts as each div refreshes.. kinda thing.. I am sure you know what I mean.
I have made a simple fiddle...
http://jsfiddle.net/ozzy/yEB4V/
Essentially, we only need ONE <li> to </li>
Reason is, we can plonk our php around the LI tags so that the loop works, and the slides get updated accordingly..
The issue I have is, the first time the LI is fired, it must not have display:none , for obvious reasons.. all the otehr subsequent occurences of the LI tags are hidden.
As you can see from the fiddle, all the LI tags have display none, apart from the first LI tag, so it shows that first, then loops to next and each one is updated.
script here;
var slider = function() {
$('#testimonials .slide').filter(':visible').fadeOut(1000,function(){
if($(this).next('li.slide').size()){
$(this).next().fadeIn(2000);
}
else{
$('#testimonials .slide').eq(0).fadeIn(1000);
}
});
};
var interval = setInterval(slider, 2000);
$('#testimonials .slide').hover(function() {
clearInterval(interval);
}, function() {
interval = setInterval(slider, 2000);
});
I wonder if anyone knows how to get around this... As our php code will be something like:
<ul id="testimonials">
<!-- OUR PHP LOOP-->
<li class="slide">
<div>
<h1><?php echo $title; ?></h1>
<p><?php echo $stuff; ?>
</div>
</li>
<!-- // PHP LOOP -->
</ul>
You could use jquery to make the first child visible.
$(document).ready(function(){
$('#testimonials :first-child.slide').show(0);
//.. rest of the stuff
});
And in the php, set all the divs to display:none
use:
<ul id="testimonials">
<?php foreach($lis as $li) { ?>
<li class="slide"<?php if($li == $lis[0]) echo ' style="display:list-item;"' ?>>
<div>
<h1><?php echo $title; ?></h1>
<p><?php echo $stuff; ?>
</div>
</li>
<?php } ?>
</ul>

jQuery Tabs - jquery script only works for 1st tab - bad initialize?

I have jQuery Tabs in which each tab and corresponding content are populated by a PHP foreach loop.
For each tab the user can upload a picture. I have this setup in a way so that as soon as the user chooses a file, a jquery script makes the upload begin automatically -- and the browse button is hidden and replaced by "Uploading your picture".
Here is the code (CI markup):
<ul class="tab_header">
<?php foreach ($p as $row):
echo '<li>
' . $row->p_name . '
</li>';
endforeach; ?>
</ul>
<?php foreach ($p as $row): ?>
<div id="tabs-<?php echo $row->p_id; ?>">
<?php echo form_open_multipart('/p/p_upload_picture/' . $row->p_id, 'id="upload_form"');
echo form_upload('userfile', '', 'id="file_select"');
echo form_hidden('upload','upload');
echo form_close(); ?>
<div id="loading" style="display:none;">
Uploading your picture...
</div>
</div>
<?php endforeach; ?>
<script>
$(function(){
$("#file_select").change(function(){
$("#upload_form").submit();
$("#upload_form_div").hide();
$("#loading").show();
});
});
</script>
This works perfectly but only on the first tab.
In all other tabs, the jquery script doesn't run -- as soon as I choose a file, the file name is shown in the browse button field instead, and no upload happens (form isn't submitted).
I wonder if this has to do with the script not being initialized for the other tabs.
How can I fix this?
Thanks for helping, much appreciated.
Your field has an id. Which should be unique per element.
jQuery only returns the first element it encounters with the given id, that's why your code isn't working. I would suggest adding a class instead of an id to your field.
$('.class-of-field')..change(function() {
..
});
The above should do the job.
This would be the equivalent code without jQuery:
var el = document.getElementById('file_select');
Which only returns one element, have a look at the documentation.

Categories