table show/hide remember the selection - php

I am a beginner and used jscript in my php page to hide/show table using the following code:
<script type="text/javascript">
function setTable(what){
if(document.getElementById(what).style.display=="none"){
document.getElementById(what).style.display="block";
}
else if(document.getElementById(what).style.display=="block"){
document.getElementById(what).style.display="none";
}
}
</script>
and display/hide table2 using:
<img src="/icons/index.png" width="55" height="55">
My problem is that while using this code, in case of any browser activity, the table is reset back to default state. I am struggling to enable users once they show/hide table it should continue even when refresh/or navigate happens within the pages. I know I should use cookies but have no idea. Please someone guide me.
thanks

Use cookies to store table state.
<script type="text/javascript">
var tableState = getCookie("table2state");
if (tableState != "") {
document.getElementById('table2').style.display = tableState;
}
function setTable(what) {
if (document.getElementById(what).style.display == "none") {
document.getElementById(what).style.display = "block";
setCookie(what + 'state', "block", 365);
} else if (document.getElementById(what).style.display == "block") {
document.getElementById(what).style.display = "none";
setCookie(what + 'state', "none", 365);
}
}
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
var expires = "expires=" + d.toUTCString();
document.cookie = cname + "=" + cvalue + "; " + expires;
}
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') c = c.substring(1);
if (c.indexOf(name) == 0) return c.substring(name.length, c.length);
}
return "";
}
</script>

Related

what can be used in place of window.location.replace to avoid page reloading?

I am using product filtering in a site like Flipkart. And I do not want to reload the page after filtering data. This is my jquery code for filtering data. Filter class is used in all the filters. Give some suggestions plz.
$('.filter').click(function() {
var typef = '';
var currentURL = location.protocol + '//' + location.host + location.pathname;
if (window.location.href.indexOf("search") > -1) {
var searchParams = new URLSearchParams(window.location.search);
var aquery = searchParams.get('query');
typef = 'search';
}
var brands = [];
var colors = [];
var price = [];
if ($(this).is(":checked")) {
$("input:checkbox[name=brand_check]:checked").each(function() {
brands.push($(this).val());
});
$("input:checkbox[name=color_check]:checked").each(function() {
colors.push($(this).val());
});
$("input:radio[name=price_check]:checked").each(function() {
price.push($(this).val());
});
var filterdata = {
brands: jQuery.unique(brands),
color: jQuery.unique(colors),
price: jQuery.unique(price)
};
var filteruri = jQuery.param(filterdata);
if (typef == 'search' && typeof aquery !== "undefined" && aquery !== '') {
window.location.replace(currentURL + '?query=' + encodeURIComponent(aquery) + '&f=' + encodeURIComponent(filteruri));
} else {
window.location.replace(currentURL + '?f=' + encodeURIComponent(filteruri));
}
} else {
$('input:checkbox[value="' + $(this).val() + '"]').attr('checked', false);
$("input:checkbox[name=brand_check]:checked").each(function() {
brands.push($(this).val());
});
$("input:checkbox[name=color_check]:checked").each(function() {
colors.push($(this).val());
});
$("input:radio[name=price_check]:checked").each(function() {
price.push($(this).val());
});
var filterdata = {
brands: jQuery.unique(brands),
color: jQuery.unique(colors),
price: jQuery.unique(price)
};
var filteruri = jQuery.param(filterdata);
if (typef == 'search' && typeof aquery !== "undefined" && aquery !== '') {
if (filteruri.length > 0) {
window.location.replace(currentURL + '?query=' + encodeURIComponent(aquery) + '&f=' + encodeURIComponent(filteruri));
} else {
window.location.replace(currentURL + '?query=' + encodeURIComponent(aquery));
}
} else {
if (filteruri.length > 0) {
window.location.replace(currentURL + '?f=' + encodeURIComponent(filteruri));
} else {
window.location.replace(currentURL);
}
}
}
});
If I understood correctly, you want to change url without page reloading.
Read some about manipulating browser history (https://developer.mozilla.org/en-US/docs/Web/API/History_API), in particular: pushState.
In your case you can use window.history.pushState (https://developer.mozilla.org/en-US/docs/Web/API/History_API#The_pushState()_method).
Instead window.location.replace you can write something like this one:
window.history.pushState({ page: filteruri }, 'Page title', currentURL + '?somethingnew');

Show a DIV based on sessions until the user closes it

I'm trying to show a DIV to the user until he/she closes it. Once the user clicks close, the DIV remains close for 24 hours.
This is the working code that shows once every 24 hours. However, I'm not sure how to add the click function:
<?php
if (!isset($_COOKIE['cookie'])) {
setcookie('cookie', true, time() + 3600 * 24); // Save a cookie for 1 day
echo '<div class="slideshow"><span class="close">close</span>Hello World</div>';
}
?>
you should try something like this.
$(document).ready(function() {
// If the 'hide cookie is not set we show the message
if (!readCookie('hide')) {
$('#popupDiv').show();
}
// Add the event that closes the popup and sets the cookie that tells us to
// not show it again until one day has passed.
$('#close').click(function() {
$('#popupDiv').hide();
createCookie('hide', true, 1)
return false;
});
});
// ---
// And some generic cookie logic
// ---
function createCookie(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}
function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
function eraseCookie(name) {
createCookie(name,"",-1);
}
code taken from here.SEE

javascript strange malfunction

I have a website that consists of index.php and otherpage.php. Both of these pages use
include_once("header.inc")
header.inc implements a jscript file like this
<script type="text/javascript" src="script.js"></script>
the jscript file lets me use a nice looking dropdown menu.
the problem is that the menu only works properly on index.php, and not otherpage.php
What is really getting me is that on otherpage.php it's not that the menu doesnt work AT ALL, it just doesn't work partly. The menu will highlight but not dropdown.
You can see for yourself
index.php
otherpage.php
Is there something about sharing a jscript file between PHP pages that I should know?
Here are the relevant jscript contents for the menu:
var menu = function() {
var t = 15, z = 50, s = 6, a;
function dd(n) {
this.n = n;
this.h = [];
this.c = []
}
dd.prototype.init = function(p, c) {
a = c;
var w = document.getElementById(p), s = w.getElementsByTagName('ul'), l = s.length, i = 0;
for(i; i < l; i++) {
var h = s[i].parentNode;
this.h[i] = h;
this.c[i] = s[i];
h.onmouseover = new Function(this.n + '.st(' + i + ',true)');
h.onmouseout = new Function(this.n + '.st(' + i + ')');
}
}
dd.prototype.st = function(x, f) {
var c = this.c[x], h = this.h[x], p = h.getElementsByTagName('a')[0];
clearInterval(c.t);
c.style.overflow = 'hidden';
if(f) {
p.className += ' ' + a;
if(!c.mh) {
c.style.display = 'block';
c.style.height = '';
c.mh = c.offsetHeight;
c.style.height = 0
}
if(c.mh == c.offsetHeight) {
c.style.overflow = 'visible'
} else {
c.style.zIndex = z;
z++;
c.t = setInterval(function() {
sl(c, 1)
}, t)
}
} else {
p.className = p.className.replace(a, '');
c.t = setInterval(function() {
sl(c, -1)
}, t)
}
}
function sl(c, f) {
var h = c.offsetHeight;
if((h <= 0 && f != 1) || (h >= c.mh && f == 1)) {
if(f == 1) {
c.style.filter = '';
c.style.opacity = 1;
c.style.overflow = 'visible'
}
clearInterval(c.t);
return
}
var d = (f == 1) ? Math.ceil((c.mh - h) / s) : Math.ceil(h / s), o = h / c.mh;
c.style.opacity = o;
c.style.filter = 'alpha(opacity=' + (o * 100) + ')';
c.style.height = h + (d * f) + 'px'
}
return {
dd : dd
}
}();
Thanks for your time
On the index.php page you are forgetting
<script type="text/javascript">
var menu = new menu.dd("menu");
menu.init("menu", "menuhover");
</script>
Put it at the bottom of otherpage.php or put it in a footer.php to be included at the bottom of the page.
seem that the second page (not the index.php) does not have the
<script type="text/javascript">
var menu = new menu.dd("menu");
menu.init("menu", "menuhover");
</script>
so the menu isn't created.
index.php includes this code at the end of the page that initializes your menu:
<script type="text/javascript">
var menu = new menu.dd("menu");
menu.init("menu", "menuhover");
</script>
otherpage.php does not include that code so the code is never initialized and hooked up to your HTML.
Incidentally, you can debug this kind of issue yourself by putting a breakpoint in the .init() method in your code. In index.php you see that the breakpoint is hit and if you look at the calling stack, you can see where it is called from. If you put the same breakpoint in otherpage.php, you can see that it is not hit, thus never called.

How to fix a not defined javascript error?

I am fairly new to Javascript and what I am trying to do is have a cookie set as soon as I click on a link. When I return back to the previous page from the link, I want the page to auto refresh and notify the user by color to show what link they just clicked. I used this example to guide me http://webdesign.about.com/od/cookies/a/aa083198.htm. But I am still not getting it.
The code below is what I have. The problem is that as soon as I click on the link firebug brings up the error "getLink not defined". Also through web developer on Firefox, it seems that my cookie is not actually being set even though I am calling it from the Html.I am also showing gave the most important part in my Html that calls the function.
The videoId i have in setCookie is a php variable that is defined somewhere else in my code. I would really appreciate it if someone can point me in the right direction. Thanks!
<head>
<script language="text/javascript">
var cookie_name = "watched";
function setCookie(cookie_name,cookie_value)
{
if (document.cookie!="") {
index = document.cookie.indexOf(cookie_name);
} else {
index = -1;
}
if (index == -1) {
var finish = 7200;
var cookie_value = videoId + "; expires=" + finish;
document.cookie=cookie_name + "=" + cookie_value;
}
}
function getLink(cookie_value) {
if (document.cookie) {
index = document.cookie.indexOf(cookie_value);
if (index != -1) {
colorLinks;
}
else{
//alert("No color");
}
}
return colorLinks;
}
function colorLinks()
{
$('#' + videoId).css('background-color: pink');
}
</script>
</head>
<body onLoad=window.refresh>
<div id="page">
echo '<a href="' . $link . '" onclick="setCookie(); return true;">' . $this->Links
This does not make sense:
function getLink(cookie_value) {
if (document.cookie) {
index = document.cookie.indexOf(cookie_value);
if (index != -1) {
colorLinks; // you mean colorLinks(); ???
}
else {
//alert("No color");
}
}
// why return a function that sets color instead of just calling it?
return colorLinks;
}
and there is luckily nothing called window.refresh (unless you have created it yourself) or you would loop forever
In the code i don't see where videoId is given a value
You don't call the function setCookie(cookie_name,cookie_value); to set the cookie.
Please read about cookies: http://www.quirksmode.org/js/cookies.html
<script type = "text/javascript">
function createCookie(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}
function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
function eraseCookie(name) {
createCookie(name,"",-1);
}
</script>

Tooltips styling issue

Hi I'm using tooltips on my site to give links and certain images hints/descriptions. I wanted for my tooltips to be able to have different styles. I pass this variable into the JS file and the code does work to an extent..
The error I am receiving is: The first rollover I make sets the style for all other rollovers, even those that are sending a variable for a different style..
Mouseover HTML
(text, size, style) - this is an example of two different onmouseovers sending a diff style
onmouseover="tooltip.show('About Us', 89,'cont1');"
onmouseover="tooltip.show('Archive', 89,'cont2');"
JS
var tooltip=function(){
var id = 'tt';
var top = 3;
var left = 3;
var maxw = 300;
var speed = 10;
var timer = 40;
var endalpha = 95;
var alpha = 0;
var tt,t,c,b,h, no;
var ie = document.all ? true : false;
return{
show:function(v,w,no){
if(tt == null){
tt = document.createElement('div');
tt.setAttribute('id',id + no);
t = document.createElement('div');
t.setAttribute('id',id + 'top');
c = document.createElement('div');
c.setAttribute('id',id + 'text');
b = document.createElement('div');
b.setAttribute('id',id + 'bot');
tt.appendChild(t);
tt.appendChild(c);
tt.appendChild(b);
document.body.appendChild(tt);
tt.style.opacity = 0;
tt.style.filter = 'alpha(opacity=0)';
document.onmousemove = this.pos;
}
tt.style.display = 'block';
c.innerHTML = v;
tt.style.width = w ? w + 'px' : 'auto';
if(!w && ie){
t.style.display = 'none';
b.style.display = 'none';
tt.style.width = tt.offsetWidth;
t.style.display = 'block';
b.style.display = 'block';
}
if(tt.offsetWidth > maxw){tt.style.width = maxw + 'px'}
h = parseInt(tt.offsetHeight) + top;
clearInterval(tt.timer);
tt.timer = setInterval(function(){tooltip.fade(1)},timer);
},
pos:function(e){
var u = ie ? event.clientY + document.documentElement.scrollTop : e.pageY;
var l = ie ? event.clientX + document.documentElement.scrollLeft : e.pageX;
tt.style.top = (u - h) + 'px';
tt.style.left = (l + left) + 'px';
},
fade:function(d){
var a = alpha;
if((a != endalpha && d == 1) || (a != 0 && d == -1)){
var i = speed;
if(endalpha - a < speed && d == 1){
i = endalpha - a;
}else if(alpha < speed && d == -1){
i = a;
}
alpha = a + (i * d);
tt.style.opacity = alpha * .01;
tt.style.filter = 'alpha(opacity=' + alpha + ')';
}else{
clearInterval(tt.timer);
if(d == -1){tt.style.display = 'none'}
}
},
hide:function(){
clearInterval(tt.timer);
tt.timer = setInterval(function(){tooltip.fade(-1)},timer);
}
};
}();
If I follow your code, it looks like your handing in style and using it as part of the name of the ID for the div your creating for the tool tip (I'm assuming your styling things based on ID name). If this is all true, it looks like your issue is that after the first tooltip is created (when tt == null at the top of your show function) you never change the ID of the tool tip after that. The ID only updates on create, so the style will not change once its created.
of course I could be completely wrong about this (I am after all out of coffee at this moment...)
Sorry for not actually answering your question, but you shouldn't invent the wheel. There're SO many libraries out there, that does the exact same thing. Here is 50 to get you started.

Categories