Is there a way to detect which tab is active using php? Reason is I want to 'reset' inactive tabs to display their default content instead of the last action performed.
I found this code that helps remembering what tab is active (after page refresh) - works great:
<script type="text/javascript">
$(function() {
// http://balaarjunan.wordpress.com/2010/11/10/html5-session-storage-key-things-to-consider/
//
// Define friendly index name
var index = 'key';
// Define friendly data store name
var dataStore = window.sessionStorage;
// Start magic!
try {
// getter: Fetch previous value
var oldIndex = dataStore.getItem(index);
} catch(e) {
// getter: Always default to first tab in error state
var oldIndex = 0;
}
$('#tabs').tabs({
// The zero-based index of the panel that is active (open)
active : oldIndex,
// Triggered after a tab has been activated
activate : function( event, ui ){
// Get future value
var newIndex = ui.newTab.parent().children().index(ui.newTab);
// Set future value
dataStore.setItem( index, newIndex )
}
});
});
You cannot detect HTML content with PHP, when the output is done the connection to the server is closed and you have no more access to the server.
The only way would be Ajax but this is nonsense for live modifiers without page reload.
You should use pure JQUery to solve that.
You could make 2 content containers, and display one original version of your content in a hidden state and one to edit.
<div id="original" style="display: none;">
original content
</div>
<div id="custom">
custom content
</div>
If you want to restore the original text you can toggle the containers display:
<script type="text/javascript">
$("#original").toggle();
$("#custom").toggle();
</script>
Or even overwrite the modified content with the original one:
<script type="text/javascript">
$("#custom").html($("#original").html());
</script>
Related
I have very limited knowledge with scripts so I hope you guys can help me with a simple solution to a small problem that I have...
I'm using the following jquery function to refresh a div with new content when a link is clicked
<script>
$(function() {
$("#myButton").click(function() {
$("#loaddiv").fadeOut('slow').load("reload.php").fadeIn("slow");
});
});
</script>
My problem is, I need to send 2 variables to the reload.php page to use in a mysql query (I have no idea how to accomplish that), also I need to make multiple links work with this function, at the moment I have multiples links with the same id and only the first link works so I guess I must associate different ids to the function in order for this to work, how can I do that?
here's the page where i'm using this: http://www.emulegion.info/teste/games/game.php
You may want to use document ready instead of function on your first line as this will make sure the code is not executed until the full page (and all elements) have loaded.
You can then use the callback functions of the fade and load to perform actions in a timely manner.
additional variables you can add after the .php, these can then be read in your reload.php file as $var1 = $_GET['var1'];
Do make sure to sanitize these though for security.
<script type="text/javascript">
// execute when document is ready
$(document).ready(function() {
// add click handler to your button
$("#myButton").click(function() {
// fade div out
$("#loaddiv").fadeOut('slow',function(){
// load new content
$("#loaddiv").load("reload.php?var1=foo&var2=bar",function(){
// content has finished loading, fade div in.
$("#loaddiv").fadeIn('slow');
}); // end load content
}); // end fade div out
}); // end add click to button
}); // end document ready
</script>
For different variables you could add a HTML5 style variable to your button.
<input type="button" id="myButton" data-var1="foo" data-var2="bar" />
You can retrieve this when the button is clicked:
// add click handler to your button
$("#myButton").click(function() {
// get vars to use
var var1 = $(this).data('var1');
var var2 = $(this).data('var2');
...
load("reload.php?var1="+var1+"&var2="+var2
if you have multiple buttons/links I would use class instead of id "myButton". that way you can apply the function to all buttons with the above script. Just replace "#myButton" for ".myButton"
First, you should use .on('click', function() or .live('click', function() to resolve your one click issue.
You'll want to do something like:
<script>
$(function() {
$("#myButton").on('click', function() {
var a = 'somthing';
var b = 'something_else';
$.post('url.php', {param1: a, param2: b}, function(data) {
//data = url.php response
if(data != '') {
$("#loaddiv").fadeOut('slow').html(data).fadeIn("slow");
}
});
});
});
</script>
Then you can just put var_dump($_POST); in url.php to find out what data is being sent.
Try creating a function that would accept parameters that you want.
Like:
$(document).ready(function(){
$('.link').click(function(){
reload(p1,p2);
});
});
function reload(param1, param2){
$("#loaddiv").fadeOut('slow').load("reload.php?param1="+param1+"¶m2="+param2).fadeIn("slow");
}
But by doing the above code your reload.php should be using $GET. Also you need to use class names for your links instead of id.
<script type="text/javascript">
// execute when document is ready
**$(document).ready(function() {**
**$("#myButton").click(function() {**
**$("#loaddiv").fadeOut('slow',function(){**
**$("#loaddiv").load("reload.php?var1=foo&var2=bar",function(){**
// content has finished loading, fade div in.
$("#loaddiv").fadeIn('slow');
});
});
});
});
</script>
$("#myButton").click(function() {
// get vars to use
var var1 = $(this).data('var1');
var var2 = $(this).data('var2');
so i have a php loop, i am using jquery slide toggle to hide/show a table with sql results. currently the table is loaded using php only, but as there is a lot going on its causing some loading problems i need to fire the ajax with the slide toggle btn, so it only requests the current items details when the button is pressed. i can get it to call the php file from the jquery but im having difficulty passing the value for each item across, so it can perform the request on the database. here is what the php foreach loop content looks like;
<span class="searchitem">
// some visible content here
<span value="item name" class="btn">button</span>
<span class="slide_area">
// hidden slide content ajax needs to populate with php result
</span>
</span>
this html is repeated i use jquery slidetoggle to hide the slide_area, what i need to do is populate the slide_area with results from php, the php file needs the name to return the results the name is passed via get with the url, so i only need append the url with the actual name from btn's value, im sure this cant be that difficult but here i am.
here's the jquery:
<script type="text/javascript">
//<![CDATA[
$(document).ready(function ()
{
$('.searchitem').each(function () {
$(this).find('.slide_area').hide();
$(this).find('.btn').click(function ()
{
var ajax_load = "<img src='images/spinner.gif' style='width:50px;' alt='loading...' />";
var loadUrl = "ajax/item.php?name=";
var loadName = $(".btn");
var Name = URLEncode(loadName);
var loadString = loadUrl + Name;
$(this).parent().find('.slide_area').slideToggle(1500).html(ajax_load).load(loadString);
});
});
});
//]]>
</script>
i need to get the value from btn and append the loadURL, im open to sending the data a different way like through post if needed, updated the jquery still not working what am i doing wrong here?
Thanks.
The easiest way would to use the Phery library http://phery-php-ajax.net/
the key here is the data-phery-remote="toggle" that will call the PHP function automatically on click, and can be reused everywhere
<span class="searchitem">
// some visible content here
<span value="item name" data-phery-remote="toggle" class="btn">button</span>
<span class="slide_area">
// hidden slide content ajax needs to populate with php result
</span>
</span>
The logic is reversed, the load will happen with only one AJAX call, instead of two.
Phery::instance()->set(array(
'toggle' => function($data){
$r = new PheryResponse;
/* do your code, fill $html_content */
$r->this()->siblings('.slide_area')->html($html_content)->toggle();
return $r;
}
))->process();
QUESTION: What is the proper way to use .get() in conjunction with .one() (or .live()) so that an external php file is appended only once?
MOST RECENT EDIT:
solution
<script>
$(document).ready(function(){
$('.tree li a').one("click", function() {
var currentAnchor = $('.tree li a').attr('href');
if(!currentAnchor){
var query = "page=1";
}
else
{
var splits = currentAnchor.substring(1).split('&');
//Get the section
var page = splits[0];
delete splits[0];
var query = "page=" + page;
alert ("page=" + page);
}
//Send the petition
$("#loading").show();
$.get("callbacks.php",query, function(data){
$("#content").append(data);
$("#loading").hide();
});
return false;
});
});
</script>
More Specifically:
I'm using Javascript and PHP to load some external PHP pages as sections in my main template.
I'm using a switch and append() so the included files keep appending. I need every file to be able to be appended ONLY ONCE. Here is the scenario as I'd like it to happen
1) downloads link is clicked
2) downloads.php appears
3) errors link is clicked
4) errors.php appears below downloads.php
5) downloads link is clicked again
6) page just scrolls up to top of downloads.php
I need the same functionality as the example on the documentation page of .one() where every div can be clicked only once.
I also looked at Using .one() with .live() jQuery and I especially liked the approach used in the accepted answer.
Iried using boolean flag as suggested below but all it did was limit my consecutive clicks on the same link to one. So if I click one link 1 multiple times it'll show page 1.php only once but if I click on link 1, then link 2, then link 1 again it will display page 1.php, then append page 2.php and append another page 1.php.
I'm starting to think that the setInterval is wrong and I may use .one() for the whole checkAnchor() function and bind it to the <a> tags. I tried this but it's not working either :(((
core.js - using .one()
var currentAnchor = null;
//$(document).ready(checkAnchor);
//Function which chek if there are anchor changes, if there are, sends the ajax petition checkAnchor
$("a").one("click", function (){
//Check if it has changes
if(currentAnchor != document.location.hash){
currentAnchor = document.location.hash;
//if there is not anchor, the loads the default section
if(!currentAnchor){
query = "page=1";
}
else
{
//Creates the string callback. This converts the url URL/#main&id=2 in URL/?section=main&id=2
var splits = currentAnchor.substring(1).split('&');
//Get the section
var page = splits[0];
delete splits[0];
var query = "page=" + page;
}
alert ("hello");
//Send the petition
$("#loading").show();
$.get("callbacks.php",query, function(data){
$("#content").append(data);
$("#loading").hide();
});
}
});
The other thing I liked as an approach is adding the names of the pages to an array and then checking that array to make sure the page wasn't displayed yet. I managed to fill up an array with the page names using .push() but I hit a dead end when looking up for a value in it. If you have an idea how that's supposed to look like that'd be very helpful as well.
core.js
///On load page
var contentLoaded;
$().ready(function(){
contentLoaded = false;
setInterval("checkAnchor()", 300);
alert (contentLoaded);
});
var currentAnchor = null;
//Function which chek if there are anchor changes, if there are, sends the ajax petition
function checkAnchor(){
//Check if it has changes
if(currentAnchor != document.location.hash){
currentAnchor = document.location.hash;
//if there is not anchor, the loads the default section
if(!currentAnchor){
query = "page=1";
}
else
{
//Creates the string callback. This converts the url URL/#main&id=2 in URL/?section=main&id=2
var splits = currentAnchor.substring(1).split('&');
//Get the section
var page = splits[0];
delete splits[0];
var query = "page=" + page;
}
alert ("hello");
//Send the petition
$("#loading").show();
alert (contentLoaded);
if (!contentLoaded){
$.get("callbacks.php",query, function(data){
$("#content").append(data);
$("#loading").hide();
});
alert (contentLoaded);
}
contentLoaded = true;
}
}
here is my
callbacks.php
<?php
//Captures the petition and load the suitable section
switch($_GET['page']){
case "4100errors" :
include 'template/4100errors.php';
break;
case "4100downloads" :
include 'template/4100downloads.php';
break;
}
?>
And my main file
4100.php
<?php
include 'template/header.php';
include 'template/4100menu.php';
include 'template/log.php';
include 'template/links.php';
include 'template/4100breadcrumbs.php';
?>
<div class="left-widget">
<div style="display:none; position:absolute; top:-9999; z-index:-100;">
</div>
<div id="side-nav-bar" class="Mwidget">
<h3>Contents</h3>
<ul class="tree">
<li><a href="#4100downloads" class="links" >Downloads</a> </li>
<li>Error Troubleshooting</li>
</ul>
</div>
</div>
<div id="content" style="margin-top:100px; margin-left:300px;">
<?
switch ($_GET['page'])
{
case "4100downloads": include 'template/4100downloads.php'; break;
case "4100errors": include 'template/4100errors.php'; break;
}
?>
</div>
</body>
</html>
4100dowloads.php
Downloads test page
4100error.php
Errors test page
Also you can look at the test page here http://period3designs.com/phptest/1/4100.php
"What is the proper way to use .get() in conjunction with .one() (or .live()) so that an external php file is appended only once?"
.one() and live() really have little to do with $.get. They're only for event handling.
If you intend to run the code every 50ms as you are, but want to replace the current content, then use .html() instead of .append().
$("#content").html(data);
This will overwrite the old content.
I assume you're aware of this, but just to be sure, your code is running at an interval because of this...
$().ready(function(){
setInterval("checkAnchor()", 50); // better--> setInterval(checkAnchor, 50);
});
If you only want it once on document load, then do this...
$(document).ready(checkAnchor);
Just use a boolean flag to determine if you loaded the data yet or not. Set it to false on page load, and just after the call to $.get set it to true. Then, wrap your $.get with an if (!contentLoaded) { $.get ... }.
That way you will execute the $.get only once.
BTW: $.one is used to bind an event to an element, that will execute only once and then unbind it self from it.
I list a lot of users on my page and I use a php function to pass the user's id and return a div pop up that displays their online status, avatar, stats etc. The problem is that the code is currently set to show the layer onmouseover and hide the layer onmouseout. I would like the code to be onclick show, and second click (either toggle on the same link or click anywhere else on the page) hide the layer but I'm not sure how to accomplish that.
The current code I'm using I got from Dynamic Drive. (sorry my tab key won't work in this text box, not sure how to fix that. feel free to edit)
SKIP TO BOTTOM
Original Method:
Javascript part
<div id="dhtmltooltip"></div>
<script type="text/javascript">
/***********************************************
* Cool DHTML tooltip script- Dynamic Drive DHTML code library (www.dynamicdrive.com)
* This notice MUST stay intact for legal use
* Visit Dynamic Drive at http://www.dynamicdrive.com/ for full source code
***********************************************/
var offsetxpoint=-60 //Customize x offset of tooltip
var offsetypoint=20 //Customize y offset of tooltip
var ie=document.all
var ns6=document.getElementById && !document.all
var enabletip=false
if (ie||ns6)
var tipobj=document.all? document.all["dhtmltooltip"] : document.getElementById? document.getElementById("dhtmltooltip") : ""
function ietruebody(){
return (document.compatMode && document.compatMode!="BackCompat")? document.documentElement : document.body
}
function ddrivetip(thetext, thecolor, thewidth){
if (ns6||ie){
if (typeof thewidth!="undefined") tipobj.style.width=thewidth+"px"
if (typeof thecolor!="undefined" && thecolor!="") tipobj.style.backgroundColor=thecolor
tipobj.innerHTML=thetext
enabletip=true
return false
}
}
function positiontip(e){
if (enabletip){
var curX=(ns6)?e.pageX : event.clientX+ietruebody().scrollLeft;
var curY=(ns6)?e.pageY : event.clientY+ietruebody().scrollTop;
//Find out how close the mouse is to the corner of the window
var rightedge=ie&&!window.opera? ietruebody().clientWidth-event.clientX-offsetxpoint : window.innerWidth-e.clientX-offsetxpoint-20
var bottomedge=ie&&!window.opera? ietruebody().clientHeight-event.clientY-offsetypoint : window.innerHeight-e.clientY-offsetypoint-20
var leftedge=(offsetxpoint<0)? offsetxpoint*(-1) : -1000
//if the horizontal distance isn't enough to accomodate the width of the context menu
if (rightedge<tipobj.offsetWidth)
//move the horizontal position of the menu to the left by it's width
tipobj.style.left=ie? ietruebody().scrollLeft+event.clientX-tipobj.offsetWidth+"px" : window.pageXOffset+e.clientX-tipobj.offsetWidth+"px"
else if (curX<leftedge)
tipobj.style.left="5px"
else
//position the horizontal position of the menu where the mouse is positioned
tipobj.style.left=curX+offsetxpoint+"px"
//same concept with the vertical position
if (bottomedge<tipobj.offsetHeight)
tipobj.style.top=ie? ietruebody().scrollTop+event.clientY-tipobj.offsetHeight-offsetypoint+"px" : window.pageYOffset+e.clientY-tipobj.offsetHeight-offsetypoint+"px"
else
tipobj.style.top=curY+offsetypoint+"px"
tipobj.style.visibility="visible"
}
}
function hideddrivetip(){
if (ns6||ie){
enabletip=false
tipobj.style.visibility="hidden"
tipobj.style.left="-1000px"
tipobj.style.backgroundColor=''
tipobj.style.width=''
}
}
document.onmousemove=positiontip
</script>
PHP part
$username = "<a onMouseover=\"ddrivetip('<Center><font class=f2>$username</font><BR>$avatarl</center>
<table align=center><Tr><Td><b>Points:</b> <font class=alttext>$user_points</font>
<BR><B>Posts:</b> <font class=alttext>$user_posts</font><BR>$user_status</td></tr></table>
<BR><img src=$icons/add-user.png height=12> <a href=$cs_url/friends/add/$user>Send Friend Request</a>
<BR><img src=$icons/user_message2.png height=12> <a href=$cs_url/messages/compose/$user>Send Message</a>
<BR><img src=$icons/user_im2.png height=12> Instant Message')\"
onMouseout=\"hideddrivetip()\">$username</a>";
My primary reason for wanting the toggle/blur as opposed to mouseout is so that users have the chance to actually click the links inside of the div layer.
The reason why I am trying to stick to this script as opposed to other ones out there I've found is because it doesn't rely on unique ids or alot of css styles. With other scripts, when I click on one username, they all of the hidden divs on the page pop up, or at least all of them for that user. This seemed to be the best for showing just one at a time.
I decided to scrap the method above. I have a script that I also got elsewhere that I use to toggle a twitter-like login in. I was wondering how I could use it to toggle the user information layer.
Second Method:
Javascript
$(".users").click(function(e) {
e.preventDefault();
$("fieldset#users_menu").toggle();
$(".users").toggleClass("menu-open");
});
$("fieldset#users_menu").mouseup(function() {
return false
});
$(document).mouseup(function(e) {
if($(e.target).parent("a.users").length==0) {
$(".users").removeClass("menu-open");
$("fieldset#users_menu").hide();
}
});
PHP part
<div id='container' class='users_container'>
<div id='usersnav' class='usersnav'> <a href='<?php echo $cs_url; ?>/users/all' class='users'><span>Fans</span></a> </div>
<fieldset id='users_menu'>
content
</fieldset>
</div>
The problem with this method as I mentioned before is that when I click on the username link, ALL of the layers for ALL of the users display on the page appear. How can I make it so that only the child layer of the parent link is displayed? Also, is there a way to toggle the layer hidden when anywhere else on the page is clicked?
Starting from your old code I assume you had something like:
elem.onmouseover = showCard;
elem.onmouseout = hideCard;
Well, from there you just need to do something along the lines of:
elem.isShown = false;
elem.onclick = function() {
if( elem.isShown) hideCard();
else showCard();
elem.isShown = !elem.isShown;
}
This ended up being the best solution though there is still one thing I wish was different about it.
This is built upon Dan's response. The reason why it wasn't working before Dan was because the user information was inside tags, I switcher username to span and the content display. The problem after that was when I clicked on one username the layer would popup but it would remain until I clicked on the same link again. So multiple layers would sometimes be on at once.
The following closes the layer when a user clicks on the layer, outside the layer or on the original link. The one little snag is that when clicking on the original link to close the layer you must click twice.
Javascript
<script type="text/javascript">
$(document).ready(function () {
$(".username").click(function () {
$(this).children().toggle();
$('.tooltip_container').hover(function(){
mouse_is_inside=true;
}, function(){
mouse_is_inside=false;
});
$(".username").click(function () {
$(this).children().toggle();
});
});
$("body").mouseup(function(){
if(! mouse_is_inside) $('.tooltip_container').hide();
});
});
</script>
PHP
<span class='username'>$username
<div class='tooltip_container'>
<div class='tooltip'>
Content goes here
</div>
</div>
</span>
I use this links and divs on my site:
<p>Menu1 | Menu2 | Menu 3|</p>
<div id="menu_1" class="mymenu">
</div>
<div id="menu_2" class="mymenu">
</div>
<div id="menu_3" class="mymenu">
</div>
And this jquery to hide and show the menu.
$('div[class*="mymenu"]').hide();
var current;
var showMenu = function(e) {
// read the id out of the clicked elements id ('navlink_ID')
var id = e.id.split('_');
$('div#menu_' + id[1]).show();
// store this element as new current visible
current = e;
}
// hide all menu elements
$('div.mymenu').hide();
$('a.navlink').click(function() {
if (this != current) {
// check if an element is visible -> hide it and show new menu
if (current) {
var id = current.id.split('_');
$('div#menu_' + id[1]).hide(200,showMenu(this));
} else {
showMenu(this);
}
}
return false;
});
How can i modify this code, if i reload the page, then the last visible DIV is stay visible. (i dont want to use query string for this. I try with jquery session but not work..)
Thank you for help...
Cookies would be the ideal way to persist your collapsible divs, ShopDev has an excellent tutorial on how to acheive the same thing as you are attempting to do, using the jQuery cookie plugin.
Basically you set a value in the cookie for each div that you want to persist and whenever the event happens you update the value in the cookie, e.g.:
$.cookie('menu_1', 'expanded');
Also you need to check when the page is first loaded the state of each div, e.g.
var menu_1 = $.cookie('menu_1');
if (menu_1 == 'collapsed') {
$('#menu_1').css("display","none");
};
Simplest pure JavaScript way: set cookie.