jQuery Accordions Using Dynamic Post ID Classes - php

I have jQuery drop down accordions on each post in my loop, and I want to trigger them individually on click. They work by checking div classes, so I've made sure that each class is dynamically named based on the post-ID. I've also created a variable to generate the name of class used in the script...
This is my code:
<script type="text/javascript">
var post_ID = ".show-dts.<?php the_ID();?>";
$(post_ID).click(function() {
if($('.show-more-dts').css('height') != '1px'){
$('.show-more-dts').stop().animate({height: '1px'}, 200);
$(this).text('Show details');
}else{
$('.show-more-dts').css({height:'100%'});
var xx = $('.show-more-dts').height();
$('.show-more-dts').css({height:'1px'});
$('.show-more-dts').stop().animate({height: xx}, 400);
// ^^ The above is beacuse you can't animate css to 100% (or any percentage). So I change it to 100%, get the value, change it back, then animate it to the value. If you don't want animation, you can ditch all of it and just leave: $('.show-more-snippet').css({height:'100%'});^^ //
$(this).text('Hide Details');
}return false;
}); </script>
Checking the page source, I can see that the jQuery code is creating the correct class names using the variable, but I'm not quite there, because when any of the accordions are clicked, all them are triggered together still.

Related

how to call wordpress function on click in a custom plugin

I've been having a go at creating a custom plugin (simplified code below).
I have my plugin file (counter.php) which has 2 function in it called
displayCount() {
// output count and a link to add 1
echo 'Add One';
}
AND
addOne() {
$count = $count + 1;
}
My question is what to I replace XXX with or how do I call addOne function from my post page?
You're attempting to modify the PHP on the user's end, but unfortunately all PHP has already run when the user is able to click the link. PHP is a server side language, Javascript is a client-side language. In order to pass data back and forth, you'll need Ajax.
However, it looks like what you're trying to do could be done with pure Javascript. Something like this:
<div id="counter"></div>
Add one
<!-- INCLUDE JQUERY HERE (or elsewhere on page, perhaps head) -->
<script type="text/javascript">
// Create global JS var to track the count.
var counter = 0;
// On document ready we need to assign a click event.
// We use document ready to be sure that we select all
// initial elements when the page is loaded.
jQuery('document').ready(function()
{
// On counter-add click...
jQuery('.counter-add').click(function()
{
// Increment counter
counter++;
// Output counter value
jQuery('#counter').text(counter);
});
});
</script>
Here is a working JSBIN copy.

jQuery.click on a div that hasn't yet loaded

I dynamically load a div on page Leagues.php with a button like this:
$("#leaguesSelectionTable th").click(function(){
var leagueSelect = $(this).attr('id');
if ($('#leaguesTable').length){
$("#loadLeagueTables").empty();
$("#loadLeagueTables").load("php/leagueTable.php?leagueSelect="+encodeURIComponent(leagueSelect));
}
else {
$("#loadLeagueTables").load("php/leagueTable.php?leagueSelect="+encodeURIComponent(leagueSelect));
}
});
This loads a table based on which button I pressed, using leagueTable.php to handle all of that. Once that table is loaded, (a bunch of leagues) I want to then be able to click on a row from this table and following the same logic, display the team table.
$("#assoc_league tr").click(function(){
var teamSelect = $(this).attr('id');
if ($('#teamsTable').length){
$("#loadTeamTables").empty();
$("#loadTeamTables").load("php/teamTable.php?teamSelect="+encodeURIComponent(teamSelect));
}
else {
$("#loadTeamTables").load("php/teamTable.php?teamSelect="+encodeURIComponent(teamSelect));
}
});
I think the problem is that since table #assoc_league is not yet present, this does not work. I tried an alert and don't get any response. This jQuery is in the same file attached to Leagues.php. Any ideas how to approach this?
Thanks.
Since your table has been added dynamically to the DOM, all the events for this table and child elements inside it will not be avaliable. In this case, you need to use event delegation :
Event delegation allows us to attach a single event listener, to a
parent element, that will fire for all children matching a selector,
whether those children exist now or are added in the future.
$('#loadLeagueTables').on('click', '#assoc_league tr', function() {
// Your code here
});

using jquery variable in php

I've got a dynamic table filled by a recordset from MYSQL.
Each row has it's own delete button (image) to delete the specific row.
This button has a class="button".
I'm using a JQuery popup modal to get a popup when a delete button is clicked.
In this JQuery script i'm creating a variable which contains the numeric value of the first td cel of the row that has been clicked on.
This all works perfectly.
What i'm trying to accomplish is to use this variable on the same php page.
Here is where my knowledge runs out.
I've read some examples where Ajax is the solution for this, but i lack the knowledge to use these examples for this solution.
JQuery code:
<script src="../javascript/jquery-1.8.2.js"></script>
<script src="../javascript/jquery.reveal.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('.button').click(function(e) { // Button which will activate our modal
var value=$(this).closest('tr').children('td:first').text();
alert(value); // this works
$('#modal').reveal({ // The item which will be opened with reveal
animation: 'fade', // fade, fadeAndPop, none
animationspeed: 500, // how fast animtions are
closeonbackgroundclick: false, // if you click background will modal close?
dismissmodalclass: 'close' // the class of a button or element that will close an open modal
});
return false;
});
});
</script>
I've been trying too much that i don't see the logic anymore.
I hope that someone can help me with this.
The issue is that your JavaScript runs in the client -- the user's web browser -- while your PHP runs on your server. It's a two-stage process: first, all the PHP is executed on the server and the HTML is rendered, which is then sent to the client (the browser). Then, the client executes all the JavaScript on the page.
You need some way to communicate the JS variable (value) to your server if you want to be able to use it in your PHP code. AJAX is one such way, but it would be helpful to have more information on how exactly you want to use this information in your PHP.
Edit: based on your comments above, something like this should work. You'll have to give your Yes button an id attribute (here I'm assuming the id is yesButton).
$(.button).click(function() {
var value=$(this).closest('tr').children('td:first').text();
$("#yesButton").attr("href", "delete_verlof.php?id=" + value);
$('#modal').reveal({ // The item which will be opened with reveal
animation: 'fade', // fade, fadeAndPop, none
animationspeed: 500, // how fast animtions are
closeonbackgroundclick: false, // if you click background will modal close?
dismissmodalclass: 'close' // the class of a button or element that will close an open modal
});
return false;
});
The important thing to note is that the JS variable does not exist yet at the time at which your PHP executes, so it is not available to the PHP. What I've done here instead is to dynamically change the href of the Yes button whenever the user clicks a td, which should have the desired effect.
If your using this in a form, then you could create a hidden input field with a unique id and add it with.
$('#idOfField').val(value);
And then use php to get the element from wherever you put it in your code.
Other then you might find attr usefull. For an example
$('#idOfField').attr('data-id', value);
Where the ID can be an div, span, i, a, bold, strong etc etc etc.

How do I slide(scroll) an entire div thats been retrieved through jquery's .load()?

So I have I this javascript that loads into a div the contents of my php (which gets data from a mysql database). When a different button is clicked, it calls the eat.php file again, with the new data to retrieve from MySQL and again loads the new data into the div.
<script type="text/javascript">
$(function() {
$("a[name=eat]").click(function() {
$("div.nav a[name=eat]").css({"background-color":"#666966","color":"#fff"});
$(".user-main").load("eat.php");
});
$("a[name=analyze]").click(function() {
$(".user-main").load("eat.php",{ name: "John", time: "2pm" });
});
});
</script>
And that is ok and everything. My question is how can I make this "slide" into the new div, like it's being scrolled horizontally? I am having no luck with the animate feature in jQuery, and would prefer not to use any frameworks. Also, is the correct way to check for a jQuery post by doing:
if (isset($_POST['name']))
in my eat.php file?
I am not quite sure what you are asking.
If you want to ensure the data you have just added is scrolled into view, then you can use code like this
if (document.all) {
document.body.scrollIntoView(false);
} else {
document.body.insertAdjacentHTML('beforeEnd','<a name="' + a + '"><\/a>');
window.location.hash = '#'+a;
}
The trick with insertAdjacentHTML is inserting a label into the screen and then telling the browser to jump to it. The label is the contents of a javascript variable which must be different each time the code is run.
If you wish to slide a whole division into view, then you will have to use a timer. Set up the div so the over-flow is hidden and it is positioned off screen, using position relative and large top or left/right values. Then, each time the timer goes off, decrease the offset towards zero.
If the timer goes off every 50ms and you move only a few pixels, you will get 20fps and it will appear quite smooth.

Loading content on a webpage only when a part of the webpage is displayed on the browser

in some pages i see when you arrive at the end of the page the page automatic loads new data. For example, some blogs when you get to the end of the page (that only loads 10 articles when you get there), the page load 10 articles more without pressing anything, so the questions will be, How do i execute/triger a php/javascript commands when something is displaying or the user gets to a particular position of the page? (USING A LOADER IMAGE OF COURSE)
--edit--
IMPORTANT: Please i dont need a triger by scroll, i need to triger from a display object, like when some image is in focus. Thanks!
Here is some code that runs on .scroll() and calculates how far from the bottom the current scroll is ..
http://jsfiddle.net/hRSE8/ (in this example, i add manually some text to showcase the effect of adding content and the scroll system adjusting to it)
At a specified distance you can load content with .ajax()
in short
$(window).scroll(function(){
var $this = $(this);
var $body = $('body');
var distance = $body.outerHeight() - $this.height() - $this.scrollTop() );
});
Update
Here is an updated example that will show when an element is in view (additional update to match specs in comment)
Demo
<script type="text/javascript">
$(document).ready(function(){
$(window).scroll(function(){
var $window = $(window);
var visibleTop = $window.scrollTop();
var visibleBottom = visibleTop + $window.height();
var elementTop = $('#myloader').offset().top;
if ( elementTop > visibleTop && elementTop < visibleBottom)
{
// loader in view
// so we remove the loader from the DOM
$('#myloader').remove();
// and run the code ..
$('#tweetsFeed').jTweetsAnywhere(
{ searchParams: ['ors=patanemo+bocaina+cuyagua+todasana+parguito+%23surfVE&lang=es&geocode=8,-66,1000km'],
count: 6 });
}
});
});
</script>
And you need to put in your page the loader with <img src="loader.gif" id="myloader" />
If you're using the jQuery framework, have a look at infinite scroll:
http://www.infinite-scroll.com/infinite-scroll-jquery-plugin/
I have never had to do this before but how I would do it is like this:
I would calculate the scroll position of the page using:
$(window).scrollTop();
Then I would find the scroll position an element on the page:
$(element selector).scrollTop()
Once the first number is bigger than the second number (plus maybe a buffer) then go ahead and make your ajax call to load whatever content you want.
This is all theoretical as I have never done but it seems logical. Anyone feel free to correct me where I might be wrong.
EDIT: You could also use the answer from this post:
Check if element is visible after scrolling
to see if an element is visible on the screen and then load at that time.
Though either of these solutions would require you to add an event handler for the scroll event.

Categories