I have this code:
$.getJSON("Featured/getEvents",
function(data){
$.each(data.events, function(i,event){
var title = event.title.substr(0,20);
$("#title-"+i).text("Text");
if ( i == 4 ) return false;
});
});
I am doing this in conjuction with a php loop to render a div 5 times, I want to place my content into the ID's from the JSON using var and the .text(), but it is not working, How do I get a var, in this case title into the jquery text() so it can place it in the corresponding div?
This is the corresponding php(partial) that this connects to:
<?php for($i = 0; $i <= 4; $i++)
{ ?>
<div id="event-item-<?= $i?>" class="event">
<div class="column-left">
<div class="title"><h3></h3></div>
This is the rendered version:
<div id="event-item-0" class="event">
<div class="column-left">
<div class="title"><h3></h3></div>
<div class="inner-left">
<img src="http://philly.cities2night.com/event/85808/image_original" class="image" width="133" height="100">
<p class="author">Posted by: <br> Brendan M. (22 Events)</p>
</div>
<div class="inner-middle">
<p class="description" id="description-0"></p>
<p class="notify"><img src="images/recommened_ico.png" alt="Recommened Event" width="98" height="21"></p>
<p class="links">
<!-- AddThis Button BEGIN -->
<img src="http://s7.addthis.com/static/btn/lg-share-en.gif" alt="Bookmark and Share" style="border: 0pt none ;" width="125" height="16"><script type="text/javascript" src="http://s7.addthis.com/js/250/addthis_widget.js?pub=philly2night"></script>
<!-- AddThis Button END -->
View Event</p>
</div>
</div>
<div class="column-right">
<ul id="event-options">
<li class="total-attending"><span>502Attending</span></li>
<li class="rsvp"><span>RSVP</span></li>
<li id="like" class="notlike"><span>(3) Likes <br><span class="message">Do You Like it?</span></span></li>
<li class="comment"><span>Comments (200)</span></li>
<li class="location"><span>Location Name</span></li>
</ul>
</div>
</div>
...
</div>
It should be as simple as referencing the variable.
$("#title-"+i).text( title );
or, if your title includes mark up,
$("#title-"+i).html( title );
If this doesn't work, make sure that you aren't getting any javascript errors that prevent the code from running.
EDIT: This may or may not be related, but I would avoid using event as a variable name. Too easy to confuse with the window.event object and it may cause other problems. Generally, I'd use evt in this case.
Other possibilities: You aren't running the getJSON method after the document is done loading or the method isn't relative to the current page. If the simple things don't seem to be getting you anywhere, you may try using Firefox/Firebug to step through the code and see what it is doing. My simple example with your mark up and just using jQuery to set the text of the anchor worked fine so I don't think the problem is in the code where the text is being set.
$(function() {
$.getJSON("/Featured/getEvents",
function(data){
$.each(data.events, function(i,evt){
var title = evt.title.substr(0,20);
$("#title-"+i).text(title);
if ( i == 4 ) return false;
});
});
});
You want to use .html(val).
Edit: Actually, .text(val) will place the text inside the element as-is. Using .html(val) will let any HTML you are adding render appropriately.
Did you try this, using title instead of "Text"?
$.getJSON("Featured/getEvents", function(data){
$.each(data.events, function(i,event){
var title = event.title.substr(0,20);
$("#title-"+i).text(title);
if ( i == 4 ) return false;
});
});
Related
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); ?>" >
}
I have a php file which is required many times, includes a small jquery snippet that is supposed to run at each instance the php file is included. However seems like jquery runs all at once in the end because I am getting variables value at once instead of at each instance. So my php file that includes another php file number of times is
base-features.php
<?php
$youtubelinks = array(
'0' => 'https://www.youtube.com/embed/NilASeqRsjw'
'1' => 'https://www.youtube.com/embed/eXG8PbwmUJw'
);
foreach($youtubelinks as $key => $val) {
$ytlink = $val;
require('youtubelink.php');
}
On my youtubelink.php I can see the $ytlink variable
<div id="page-corporate-video-overlay" class="page-corporate-video-overlay">
<div class="container">
<div class="row block">
<div class="col-md-12">
<?php print $ytlink ?>
<p><span class="video-play-icon"></span><p>
</div>
</div>
</div>
</div>
<div class="page-corporate-video">
<div class="container">
<div class="row">
<div class="col-md-12">
<div class="inner">
<iframe id="corporate-video" class="page-corporate-video-iframe" width="100%" height="100%" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>
</div>
</div>
</div>
</div>
</div>
<!--The jquery script I am having problem with-->
<script type="text/javascript">
jQuery(document).ready(function() {
var videoYoutube = "<?php print $ytlink; ?>"
$('.page-corporate-video-overlay').click(function() {
$('html, body').animate({
scrollTop: $(this).closest("div.page-corporate-video-overlay").offset().top-15
}, 500);
$(this).hide();
console.log(videoYoutube);
$(this).closest('div.base-feature').css({'background-image':'none','height':'auto'});
$(this).next('div.page-corporate-video').find('.page-corporate-video-iframe').attr('src',videoYoutube+"?controls=0&rel=0&showinfo=0&enablejsapi=1&autoplay=1&modestbranding=1&theme=light");
$(this).next('div.page-corporate-video').show();
});
});
So when I click on .page-corporate-video-overlay', I get two values of thevideoYoutube` variable. This is causing me problems to embed the right video onto the iframe as only last value gets embedded instead of each iframe getting relative youtube variable value during the each loop instance.
Thanks to #freedomn-m 's comment I refactored my code according to his suggestion.
Refactored youtubelink.php
Everything is almost the same except I added an extra attribute on the div.page-corporate-video-overlay of data-ytlink ="<?php print $ytlink;?>" and on my Jquery within my click function event I added
var videoYoutube = $(this).attr('data-ytlink');
Now I am able to embed videos correctly.
I want to relate the width of two elements, the first is a simple div, the second is a span.
<div id="wb_Name_To_Menu" style="position:absolute;left:768px;top:20px;width:171px;height:18px;z-index:4;">
<span id="sp_Name_To_Menu" style="color:#FF0000;font-family:Arial;font-size:16px;">Love Me!</span></div>
<div id="Layer_to_mainu" style="visibility: hidden;position:absolute;text-align:left;left:772px;top:22px;width:132px;height:135px;z-index:132;" title="">
<div id="wb_main_mainu" style="position:absolute;left:8px;top:9px;width:123px;height:28px;z-index:1128;padding:0;">
<div id="main_mainu">
<ul style="display:none;">
<li><span></span><span id="id_full_name_from_main_menu">love Meeeeee</span>
<ul>
<li><span></span><span>Account Sitting</span></li>
<li><span></span><span>Help</span></li>
<li><span></span><span>Log Out</span></li>
</ul>
</li>
</ul>
</div>
in JavaScript:
$(document).ready(function(){
$("#wb_Name_To_Menu").hover(function(){
$("#Layer_to_mainu").css("visibility","visible");
$("#Layer_to_mainu").css("width",$("#id_full_name_from_main_menu").width()+"px");
});
});
$(document).ready(function(){
$("#Layer_to_mainu").mouseleave(function(){
$("#Layer_to_mainu").css("visibility","hidden");
});
});
it doesn't work! and I know the cause: it is caused by $("#id_full_name_from_main_menu").width() which results in a null value!
$("#id_full_name_from_main_menu").width() returns 0 because its ancestor <ul> has display:none set. To read the width you might want to just remove that attribute, or you could temporarily change it in the js, depending on what you're trying to do
$(document).ready(function(){
$("#wb_Name_To_Menu").hover(function(){
$("#Layer_to_mainu").css("visibility","visible");
$("#main_mainu > ul").css("display","block");
$("#Layer_to_mainu").css("width",$("#id_full_name_from_main_menu").width()+"px");
$("#main_mainu > ul").css("display","none");
});
That won't display your text but it will update the width of #id_full_name_from_main_menu,
you would need to remove the display:none to see your text appear.
If you remove +"px" On line 4 of the script you provided it seems to work.
$("#Layer_to_mainu").css("width",$("#id_full_name_from_main_menu").width());
Im trying to make a left side navigation that slides down with sub categories when you click on one of the links.
I've got it to work for the top link only but the others dont work.
In my header file I have some jquery script like this:
<script>
$(document).ready(function(){
$("#flip").click(function(){
$("#panel").slideToggle("slow");
});
});
</script>
in my HTML/PHP i have this code:
<div id="left-prod-nav">
<ul>
<li class="top">Product Categories</li>
<?for($i = 0; $i < $count; $i++)
{?>
<div id="flip"><li><img src="images/arrowright_off.gif" style="padding:0px; margin:0px;float:right;"><?=$result[$i]['categoryName']?></li> </div>
<div id="panel">Hello world!</div>
<?}?>
</ul>
<div class="clear"> </div>
</div>
so the navigation is there...and when I click on the top one, the others slide down so you can see the sub categories for the one I clicked.
however if I click any of the others nothing happens.
has anyone had this problem before or know how to solve it looking at my code?
Thanks
I can assume you are trying to accomplish something like this: http://jsfiddle.net/QQRy8/
$(".flip").click(function(){
$(this).next(".panel").slideToggle("slow");
});
I changed your jQuery to use classes, you should change your PHP to give each div a class name instead of an ID (ID's must be unique!)
This answer is based off this HTML:
<div class="flip">
<li>
cool
</li>
</div>
<div class="panel" style="display: none;">Hello world!</div>
So I have a website that navigates by scrolling through a pane of DIVs that's wrapped inside a main DIV via. JQuery/javascript: http://plugins.jquery.com/project/ScrollTo
E.g.
<div id="content" style:"overflow:hidden; width 800px;">
<div id="home" class="page"></div>
<div id="about" class="page"></div>
<div id="support" class="page"></div>
</div>
It navigates and scrolls fine, but attempting to provide dynamic URLs for the pages without breaking the scrolling feature (e.g. mywebsite.com?p=home) brings a bit of trouble.
So depending on what the GET request returns, I want the PHP script to automatically set the scroll position on page load; as the scroll bars are hidden, and can only be set via. javascript.
What is the best method for this?
Probably something like this
<script>
var goTo = '<?php echo (isset($_GET['p']) ? $_GET['p'] : "default_value"); ?>';
(function($){
$(document).ready(function(){
functionThatScrolls(goTo);
});
}(jQuery));
<script>
I would do it like this, just print the value of the $_GET['p'] into the script, just make sure to print a default value, and maybe sanitize the value of p someone could insert something into it.
hope it helped.
May I suggest simply using plain old anchor tags?
The way you've described your site doesn't seem to need all this js magic in order to achieve the effect you're looking for...
<div>
<a name="home">
<div>
</div>
</a>
<a name="pix">
<div>
</div>
</a>
<a name="about us">
<div>
</div>
</a>
<a name="contact">
<div>
</div>
</a>
</div>
Then, links to http://www.mywebsite.com/#home will go do what you're looking for, plus google will index it as a subsection of http://www.mywebsite.com/
I think if you put a ! before your anchor tag names, google will actually index each as a separate page.
EDIT: Go here, and scroll down to "Step-by-step guide".
Here is something I use to get the $_GET vars:
function getQueryParams(qs) {
qs = qs.split("+").join(" ");
var params = {},
tokens,
re = /[?&]?([^=]+)=([^&]*)/g;
while (tokens = re.exec(qs)) {
params[decodeURIComponent(tokens[1])]
= decodeURIComponent(tokens[2]);
}
return params;
}
var $_GET = getQueryParams(document.location.search);
$(document).ready(function(){
$('html,body').animate({
scrollTop: $('#'+$_GET.p).offset().top},
'slow');
});