I used the function toggle I would like that if I refresh the page, it remember the position of the toggle.
I try to use the session but I can't find the way to update the session (when the user want to see more or less).
Here is my code:
<script language="javascript">
function toggle(showHideDiv, switchImgTag) {
var ele = document.getElementById(showHideDiv);
var imageEle = document.getElementById(switchImgTag);
if(ele.style.display == "block") {
ele.style.display = "none";
imageEle.innerHTML = '<img src="more.png"">';
}else {
ele.style.display = "block";
imageEle.innerHTML = '<img src="less.png">';
}
}
</script>
<?php
if(empty($_SESSION["toggle"])){
$_SESSION["toggle"] = 'show';
}?>
<a id="imageDivLink" href="javascript:toggle('contentDivImg', 'imageDivLink');"><img src="lesss.png"></a>Title
<?php if($_SESSION["toggle"] == 'show'){ ?>
<div id="contentDivImg" style="display: block;">
<?php
$_SESSION["toggle"] = 'hidden';
}
if($_SESSION["toggle"] == 'hidden'){ ?>
<div id="contentDivImg" style="display: none">
<?php $_SESSION["toggle"] = 'show';
} ?>
Try Show & hide
</div>
I second #Akam and #ChaseMoskal suggesting you use JavaScript for this.
It should be as simple as
<html>
<head>
<script type="text/javascript">
function toggle(showHideDiv, switchImgTag) {
var ele = document.getElementById(showHideDiv);
var imageEle = document.getElementById(switchImgTag);
if(ele.style.display == "block") {
// Also set the toggle cookie on toggle
document.cookie = 'toggle=hide'
ele.style.display = "none";
imageEle.innerHTML = '<img src="more.png"">';
}else {
// Also set the toggle cookie on toggle
document.cookie = 'toggle=show'
ele.style.display = "block";
imageEle.innerHTML = '<img src="less.png">';
}
}
</script>
</head>
<body>
<a id="imageDivLink" href="javascript:toggle('contentDivImg', 'imageDivLink');"><img src="lesss.png"></a>Title
<div id="contentDivImg" style="display:block">Try Show & hide</div>
<script type="text/javascript">
// Run at the end of the body so that the dom is ready for us
// Dont beleave me? reade this: https://groups.google.com/forum/#!topic/closure-library-discuss/G-7Ltdavy0E
(function(){
// Get the cookie we want to check using a fancy-pants regex
var cookie = document.cookie.replace(/(?:(?:^|.*;\s*)toggle\s*\=\s*([^;]*).*$)|^.*$/, "$1");
if (cookie === 'hide')
// If the cookie says hide, just use the toggle function
// The user wont see the change because were still running way before readystate complete
toggle('contentDivImg', 'imageDivLink');
}())
</script>
</body>
</html>
This uses document.cookie to set a toggle cookie to either show or hide.
If the toggle cookie is hide then the toggle function gets called before the page finishes loading.
Note that while this will work when the file is served from a remote server (or localhost) over http(s), it won't work if the file is retrieved using the file: protocol because cookies are associated with a domain.
If you want to learn more about using cookies in JavaScript or just want to copy and past some useful functions (and even a small framework) check out the MDN article
Related
I am using the following code, for loading contents without loading the page !
index.html
<html>
<head>
<script type="text/javascript">
// <![CDATA[
document.observe('dom:loaded', function () {
var newsCat = document.getElementsByClassName('newsCat');
for(var i = 0; i < newsCat.length; i++) {
$(newsCat[i].id).onclick = function () {
getCatPage(this.id);
}
}
});
function getCatPage(id) {
var url = 'load-content.php';
var rand = Math.random(9999);
var pars = 'id=' + id + '&rand=' + rand;
var myAjax = new Ajax.Request(url, {
method: 'get',
parameters: pars,
onLoading: showLoad,
onComplete: showResponse
});
}
function showLoad() {
$('newsContent').style.display = 'none';
$('newsLoading').style.display = 'block';
}
function showResponse(originalRequest) {
var newData = originalRequest.responseText;
$('newsLoading').style.display = 'none';
$('newsContent').style.display = 'block';
$('newsContent').innerHTML = newData;
}
// ]]>
</script>
</head>
<body>
<div class="newsCat" id="newsCat1">Politics</div>
<div class="newsCat" id="newsCat2">Sports</div>
<div class="newsCat" id="newsCat3">Lifestyle</div>
<div id="newsLoading">Loading
<img src="loading_indicator.gif" title="Loading..." alt="Loading..." border="0" />
</div>
<div id="newsContent"></div>
</div>
</body>
</html>
this page is for including the desired page in the index.php !
content-load.php
<?php
function stringForJavascript($in_string) {
$str = preg_replace("# [\r\n] #", " \\n\\\n", $in_string);
$str = preg_replace('#"#', '\\"', $str);
return $str;
$user = $_SESSION['userName'];
}
switch($_GET['id']) {
case 'newsCat1':
$content = include("politics.php");
break;
case 'newsCat2':
$content = include("sports.php");
break;
case 'newsCat3':
$content = include("lifestyle.php");
break;
default:
$content = 'There was an error.';
}
print stringForJavascript($content);
usleep(600000);
?>
PROBLEM FACING
it works fine, but when i am refreshing the page or submitting a form, the code refreshes, i mean the page which was include before refreshing, doesnot exists......
and i am really sorry about my ENGLISH, i know its horrible ! :)
pls help me php masters, i need ur help...
There are two ways to slove that problem.
You could do that on the client site with an hashtag what is curriently loaded and rebuild the page with that data or:
use the pushState API to manipulate the shown url in the address bar. Then you need to return the right data from the server after a reload.
This is behaviour by design. The Reload button will really reload the page - this includes resetting the page state.
In a freshly loaded page, you do not display a category - this is triggered only by user interaction after the page has finished loading.
A common workaraound is to store the chosen category in a cookie, auto-trigger the category load after the page has initialized.
The PHP:
<?php
$mainView = "views/dashboardView.php";
?>
The HTML:
<div class="mainContent">
<?php include($mainView); ?>
</div>
I would like the click event of a button to change what view .mainContent shows and I believe AJAX can accomplish this but as yet have not been able to get it to work.
Any advice?
You would have to modify your PHP script to allow for this.
For example:
PHP:
if (isset($_POST['change']))
{
$mainView = $_POST['change'];
echo $mainView;
}
HTML & jQuery:
<button id="change">Change the var</button>
<script>
$("#change").click(function() {
$.post("file.php", {change: $(this).val()},
function (data)
{
$("#mainContent").html(data);
});
});
</script>
<script type="text/javascript>
function changePage(pageDest){
var xmlobject = (window.XMLHttpRequest) ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
xmlobject.onreadystatechange = function (){
if(xmlobject.readyState == 4 && xmlobject.status == 200){
document.getElementById("mainContent").innerHTML = xmlobject.responseText;
}
else{
document.getElementById("mainContent").innerHTML = 'Loading...';
}
}
xmlobject.open("GET",pageDest,true);
xmlobject.send();
}
</script>
<div class="mainContent" id="mainContent">
Change this HTML
</div>
<div onmouseup="changePage('views/dashboardView.php')">Get dashboard view</div>
The parameter in the changePage function is the location of the page that you would like to place in your mainContent <div>
Does this help?
You cannot change the value of a PHP variable, as PHP is Server Side (done first), and JS is Client Side (done after Server Side).
Typically AJAX is used to repopulate an area of a web page, but that would suit your purpose. In the example below, ajax/test.php is the new file you want to include. Obviously change the path/name as you wish, and create that file.
I will add though, if you are repopulating a large chunk of your page, it will probably be just as quick to fully reload it.
$(function(){
$('.your-button-class').on('click', function(){
$.post('ajax/test.php', function(data) {
$('.mainContent').html(data);
});
});
});
Storing the View in the session, will keep the site displaying this view until the user closes the browser and ends the session, the session expires or they change the view again.
The include that sets mainView
<?php
session_start();
$mainView = "views/dashboardView.php"; // default
if(isset($_SESSION['mainView']))
{
$mainView =$_SESSION['mainView'];
}
?>
// the ajax script that sets the mainView
<?php
session_start();
$_SESSION['mainView']='views/'.$_GET['mainView'].'.php';
?>
the javascript link for ajax
ajaxURL='ajax.php?mainView=otherDasboard';
you may also want to check for empty session variable and that the file exists before setting it
Here's my code:
<script type="text/javascript">
(function() {
window.PinIt = window.PinIt || { loaded:false };
if (window.PinIt.loaded) return;
window.PinIt.loaded = true;
function async_load(){
var s = document.createElement("script");
s.type = "text/javascript";
s.async = true;
if (window.location.protocol == "https:")
s.src = "https://assets.pinterest.com/js/pinit.js";
else
s.src = "http://assets.pinterest.com/js/pinit.js";
var x = document.getElementsByTagName("script")[0];
x.parentNode.insertBefore(s, x);
}
if (window.attachEvent)
window.attachEvent("onload", async_load);
else
window.addEventListener("load", async_load, false);
})();
</script>
<!-- Customize and include for EACH button in the page -->
Pin It
The php successfully gathers all of the elements and when I click on the button, it pops up the modal window.
However, in the subsequent modal window, it does not pin to my board when I'm logged in.
The Script tag and link are both inside of a list item.
Any help would be appreciated.
Thanks,
Moises M.
From your description it sounds like the problem is that you are not url encoding the parameters, i.e. everything after the ?url=
I'm not sure if that's the only problem you'll run into with this, but it should fix the one you're currently hitting!
I want to toggle divs by clicking on links. but things are not going well for me when I click on a link it shows a new div but don hide the previous one
JavaScript Code
<script type="text/javascript">
function toggle(id){
var el = document.getElementById(id);
if(el != null && el.style["display"]== 'none'){
el.style["display"] = "block";
}
}
</script>
My divs code
<?php foreach($titles_data as $title){ ?>
<div style="display:none" id="content_<?php echo $title['idtitles'] ?>">
<div id="left-ad"></div>
</div>
<?php } ?>
My links code
<?php foreach($titles_data as $title){ ?>
<li class="flag_<?php echo strtoupper($title['language']) ?>">
<a id="title_<?php echo $title['idtitles'] ?>" href="" title="<?php echo $title['title'] ?>" onclick="toggle('content_<?php echo $title['idtitles'] ?>')">
</a>
</li>
<?php } ?>
How can it be done so that when i click on link its respective iv becomes visible and the previous one hides?
Thanks
Using native JS:
function toggle(id){
var el = document.getElementById(id);
el.style.display = el.style.display == "none" ? "block" : "none";
}
toggle("myId");
Using jQuery:
function toggle(selector) {
$(selector).toggle();
}
toggle("#myId");
To toggle the display, you dont need to do that much
$("#elementid").toggle();
In reference to your question
$('a').click(function() { // however this is select all anchors, better use class
// selector like $(".mylinkclass")
var id= $(this).attr('id'); //get the id
var ids = id.splite("_"); //split the id on "_", to extract the idtitles
$("#content_"+ids[0]).toggle(); // use that to toggle
});
Assuming that there is always only one div that is displayed, you can check for it:
Alter your logic, to declare a global variable to hold the value of the currently visible div. And then update that variable whenever a link is clicked, to hold the id of the currently visible div. So, using your exisitng code, you can do this :
using core javascript:
var visibleDiv;
function toggle(id){
// hide the previous div using visibleDiv
if(document.getElementById(visibleDiv)!= null) document.getElementById(visibleDiv).style["display"] = "none";
var el = document.getElementById(id);
if ( el.style["display"] == "" || el.style["display"] == 'none' ){
el.style["display"] = 'block';
}
visibleDiv = id; // update the current visible div name
}
using jquery like this :
var visibleDiv;
$("[id^=content_]").each(function() {
if($(this).is(':visible')){
visibleDiv = $(this).attr('id');
}
});
Check my new answer. I just created the sample html page, with 3 divs. Initially all are shown. When you click on one of them, it is hidden. When you click on some other div. The old one is made visible again and the current one is hidden. Modify the logic as per your requirements.
<html>
<head>
<title>asdsa</title>
<script type="text/javascript">
var visibleDiv;
function toggled(id){
//$('#div_2').html($('#div_1').html());
if(document.getElementById(visibleDiv) != null){ document.getElementById(visibleDiv).style["display"] = "block";}
var el = document.getElementById(id);
document.getElementById(id).style["display"] = "none";
visibleDiv = id;
}
</script>
</head>
<body>
<div id="div_1" onclick="toggled('div_1')">div1</div>
<div id="div_2" onclick="toggled('div_2')">div2</div>
<div id="div_3" onclick="toggled('div_3')">div3</div>
<hr/>
</body>
</html>
Thanks.
I have a jquery colorbox (lightbox) that pops up when users click a button on my page. Under certain conditions though i want this colorbox to appear without the user having to click a button. For example when the page is loaded and variable is passed in the query string I want to pop up the colorbox.
For example the following code shows how when user clicks the signup button the colorbox appears (this is for a page called example.php)
<p class="signup_button"><img src="images/buttons/sign_up_now.gif" alt="Sign Up Now"></p>
<script type="text/javascript">
$('.free_signup_link').colorbox({href:"signup.php?type=5"});
</script>
What I want to do is if the page is loaded with a variable in the query string then the colorbox is automatically shown (eg for example.php?show=1)
if($_GET['show'] == "1") {
// show the color box
}
Anyone know how to do this?
thanks
This should work, it's probably considered a bit "dirty" however.
<?php
if($_GET['show'] == "1") { ?>
<script type="text/javascript">
$.colorbox({href:"signup.php?type=5"});
</script>
<?php } ?>
Why not just use jQuery?
function getUrlVars() {
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for(var i = 0; i < hashes.length; i++)
{
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}
var show = getUrlVars()["show"];
if(show == 1) {
$.colorbox({href:"signup.php?type=5"}).click();
}
Reference: http://jquery-howto.blogspot.com/2009/09/get-url-parameters-values-with-jquery.html
How about this?
if($_GET['show'] == "1") {
echo '
<script type="text/javascript">
$.colorbox( ... ); // or whatever that triggers the colorbox
</script>
';
}