hiding php created divs during onload with javascript - php

I am running the javascript function shoh() below on page load to hide div's. This works fine on html hard coded divs but appears not to be working on divs that are created via php. Am I correct in assuming that the javascript runs first before the php creates the divs and that is why they aren't being hidden? If so, is there any other way to hide these divs after they are created? They need to be shown by default in case javascript is disabled?
code which runs with onload:
<script type="text/javascript">
function closeAllDivs() {
shoh('g1');
shoh('g2');
shoh('g3');
shoh('g4');
}
</script>
<BODY onLoad="closeAllDivs();">
javascript to hide divs:
function shoh(id) {
if (document.getElementById) { // DOM3 = IE5, NS6
if (document.getElementById(id).style.display == "none"){
document.getElementById(id).style.display = 'block';
filter(("img"+id),'imgin');
} else {
filter(("img"+id),'imgout');
document.getElementById(id).style.display = 'none';
}
} else {
if (document.layers) {
if (document.id.display == "none"){
document.id.display = 'block';
filter(("img"+id),'imgin');
} else {
filter(("img"+id),'imgout');
document.id.display = 'none';
}
} else {
if (document.all.id.style.visibility == "none"){
document.all.id.style.display = 'block';
} else {
filter(("img"+id),'imgout');
document.all.id.style.display = 'none';
}
}
}
}
php code which creates divs:
for ($i=0; $i < count($this->items); $i++){
<div style="display: block;" id="g<? echo $i ?>">
... code that displays items
</div>
}

It shouldn't really matter so much whether the php made the divs or whether they're hardcoded - by the time the HTML hits the browser, it's already the same thing. The server processes the PHP - by the time it leaves the server and heads to the browser, there is no PHP anymore.
I'd recommend using window.onload instead of a <body onload="">
window.onload = function() {
closeAllDivs();
};

Thanks to Wolfman Joe for letting me know the problem was likely not with the order of things. This told me the shoh() function was likely failing and therefore interrupting execution... so the code to close the divs was never executed. The solution was to build a check into the shoh() function to first make sure the div existed before attempting to change its property. As it turns out, not all divs $i were being created.
function shoh(id) {
if (document.getElementById) { // DOM3 = IE5, NS6
if (document.getElementById(id)){
if (document.getElementById(id).style.display == "none"){
document.getElementById(id).style.display = 'block';
filter(("img"+id),'imgin');
} else {
filter(("img"+id),'imgout');
document.getElementById(id).style.display = 'none';
}
}
}
}

Related

How to run multiple functions in JQuery?

Have two functions in my index.php file, they work fine, but will only execute the last one. They work fine when one is commented out or the order is swapped, my question is how can I get them to both run if this is possible.
// ************************* Scroll Up Button *************************
// Get the button
var mybutton = document.getElementById("scrollTopBtn");
// When the user scrolls down 20px from the top of the document, show the button
window.onscroll = function() {scrollFunction()
console.log('Scroll To Top Button');
};
function scrollFunction() {
if (document.body.scrollTop > 20 || document.documentElement.scrollTop > 20) {
scrollTopBtn.style.display = "block";
} else {
scrollTopBtn.style.display = "none";
}
}
// When the user clicks on the button, scroll to the top of the document
function topFunction() {
document.body.scrollTop = 0;
document.documentElement.scrollTop = 0;
}
// ********************** Sticky navbar **********************************
window.onscroll = function() {stickyHeaderScroll()};
var header = document.getElementById("navBack");
var sticky = header.offsetTop;
function stickyHeaderScroll() {
if (window.pageYOffset > sticky) {
header.classList.add("sticky");
} else {
header.classList.remove("sticky");
}
}
For the example above the navbar will remain sticky but the scroll to top button won't appear, if I swap the code then scroll button will appear and work but navbar won't remain sticky. I've tried adding the sticky navbar code into the navbar.php, but still get the same problem.
I know I'm missing something really obvious here, but the other answers I've looked at don't seem to work.
You can add both function at once
// ************************* Scroll Up Button *************************
// Get the button
var mybutton = document.getElementById("scrollTopBtn");
function scrollFunction() {
if (document.body.scrollTop > 20 || document.documentElement.scrollTop > 20) {
mybutton.style.display = "block"; // here was used worng object
} else {
mybutton.style.display = "none";
}
}
// When the user clicks on the button, scroll to the top of the document
function topFunction() {
document.body.scrollTop = 0;
document.documentElement.scrollTop = 0;
}
// ********************** Sticky navbar **********************************
var header = document.getElementById("navBack");
var sticky = header.offsetTop;
function stickyHeaderScroll() {
if (window.pageYOffset > sticky) {
header.classList.add("sticky");
} else {
header.classList.remove("sticky");
}
}
// When the user scrolls down 20px from the top of the document, show the button
window.onscroll = function() {
if(typeof scrollFunction === "function") {
scrollFunction();
}
if(typeof stickyHeaderScroll=== "function") {
stickyHeaderScroll();
}
console.log('Scroll To Top Button');
};
or use window.addEventListener('scroll', functionName)
window.addEventListener('scroll', scrollFunction);
window.addEventListener('scroll', stickyHeaderScroll);

PHP & MySql and Ajax auto-suggest issue

I'm using bootstrap for website. I include Ajax, css and PHP to show Auto Suggestions for mp3 search. Everything is working fine but an issue happened. I tried with different way but the issue is still there.
The Issue
When type keyword it show suggestion. (OK)
When you click on keyword from suggestion it works. (OK)
But when we erase keyword and click on anywhere at page then page content reload and shown as u can see in picture.
Url of website is http://www.4songs.pk
Code in header
<script src="http://www.4songs.pk/js/jquery-1.10.2.js"></script>
<script>
$(function(){
$(document).on( 'scroll', function(){
if ($(window).scrollTop() > 100) {
$('.scroll-top-wrapper').addClass('show');
} else {
$('.scroll-top-wrapper').removeClass('show');
}
});
$('.scroll-top-wrapper').on('click', scrollToTop);
});
function scrollToTop() {
verticalOffset = typeof(verticalOffset) != 'undefined' ? verticalOffset : 0;
element = $('body');
offset = element.offset();
offsetTop = offset.top;
$('html, body').animate({scrollTop: offsetTop}, 500, 'linear');
}
</script>
<script type="text/javascript">
var myAjax = ajax();
function ajax() {
var ajax = null;
if (window.XMLHttpRequest) {
try {
ajax = new XMLHttpRequest();
}
catch(e) {}
}
else if (window.ActiveXObject) {
try {
ajax = new ActiveXObject("Msxm12.XMLHTTP");
}
catch (e){
try{
ajax = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {}
}
}
return ajax;
}
function request(str) {
//Don't forget to modify the path according to your theme
myAjax.open("POST", "/suggestions", true);
myAjax.onreadystatechange = result;
myAjax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
myAjax.setRequestHeader("Content-length", str .length);
myAjax.setRequestHeader("Connection", "close");
myAjax.send("search="+str);
}
function result() {
if (myAjax.readyState == 4) {
var liste = myAjax.responseText;
var cible = document.getElementById('tag_update').innerHTML = liste;
document.getElementById('tag_update').style.display = "block";
}
}
function selected(choice){
var cible = document.getElementById('s');
cible.value = choice;
document.getElementById('tag_update').style.display = "none";
}
</script>
The 2nd issue
When auto suggestions load it also include some empty tags as you can see in picture
I take this picture as doing Inspect Elements
PHP Code are clean
<?php
include('config.php');
if(isset($_POST['search']))
{
$q = $_POST['search'];
$sql_res=mysql_query("SELECT * FROM dump_songs WHERE (song_name LIKE '%$q%') OR (CONCAT(song_name) LIKE '%$q%') LIMIT 10");
while($row=mysql_fetch_array($sql_res))
{?>
<li><a href="javascript:void(0);" onclick="selected(this.innerHTML);"><?=$row['song_name'];?></li>
<?php
}
}?>
In the function request(str) put an if statement to check if str length is greater than zero.
function request(str) {
if(str.length > 0)
{
// Your existing code
}
else
{
document.getElementById('tag_update').innerHTML = '';
}
}
In short words the problem you are describing is happping because the str parameter in the data that you send to /suggestions is empty. The server returns 304 error which causes a redirect to the root page. Your js script places the returned html into the suggestion container. And thats why you are seeing this strange view.
-UPDATE 1-
Added the following code after user request in comments
else
{
document.getElementById('tag_update').innerHTML = '';
}
-UPDATE 2- (16/07/2014)
In order to handle the second issue (after the user updated his question)
Υou forgot to close the a tag in this line of code
<li><a href="javascript:void(0);" onclick="selected(this.innerHTML);"><?=$row['song_name'];?></li>

Javascript code that doesn't work without an alert before it, otherwise it works perfectly

I've tried to really look this one up before asking a question but it looks like I am in a bind here and would like to see if someone knows a clear definite answer to this problem. I've seen like one or two similar questions but they didn't seem to point out my problem or at least I didn't understand what they were going for.
I am working on an RPG system audio PHP function that plays music when called on and it uses the audio tag if the user doesn't have their music option on mute. (in the function $song is the song thrown into the first argument.) Now if this function is called to have resume to be true then it uses some javascript. Excuse the code as it is a bit messy (to me) but here's the following code that includes the javascript code:
function playmusic($song, $resume=false, $loop=true)
{
global $baseurl, $loggeduser;
if ($resume == true)
{
$buttons = "
<button onclick=\"resetplaytime()\" type=\"button\">Reset</button>
<button onclick=\"alertplaytime()\" type=\"button\">Alert Time</button>";
$resume = "
<script type=\"text/javascript\">
var curmusic_$song = document.getElementById(\"music_$song\");
var musictime = getcookie(\"musicplaytime_$song\");
if (musictime != null && musictime != \"\")
{
alert(musictime);
curmusic_$song.currentTime = musictime;
}
window.onload=settimecookie();
function getcookie(c_name)
{
var i,x,y,ARRcookies=document.cookie.split(\";\");
for (i=0;i<ARRcookies.length;i++)
{
x=ARRcookies[i].substr(0,ARRcookies[i].indexOf(\"=\"));
y=ARRcookies[i].substr(ARRcookies[i].indexOf(\"=\")+1);
x=x.replace(/^\s+|\s+$/g,\"\");
if (x==c_name)
{
return unescape(y);
}
}
}
function settimecookie()
{
var playtime = curmusic_$song.currentTime;
if (playtime != null && playtime != \"\")
{
document.cookie = 'musicplaytime_$song=' + playtime;
}
setTimeout(\"settimecookie()\", 50);
}
function alertplaytime()
{
alert(musictime);
}
function resetplaytime()
{
curmusic_$song.currentTime=0;
}
</script>";
}
if ($loop == true)
{
$songloop = " loop=\"true\"";
}
if ($loggeduser['mutemusic'] == 0)
{
return "
</table>
$buttons
<audio id=\"music_$song\" autoplay=\"true\"$songloop preload=\"true\">
<source src=\"$baseurl/boardfiles/effects/$song.ogg\" type=\"audio/ogg\" />
<source src=\"$baseurl/boardfiles/effects/$song.mp3\" type=\"audio/mp3\" />
</audio>
$resume
<table class=\"brdr\" cellpadding=\"0\">";
}
}
Now if I take the alert out of the loop that sets the audio tag's playtime to the cookie value, the whole script doesn't work (as in nothing being done) unless you use a button to call one of the functions directly and then that function works.
I've tried a few things from making this a function and calling it directly (it seems to only work with onclick events but if you expect it to run while onload or some automatic event then it fails.), moving it around later in the function (along with the onload for settimecookie() as it has to be after this because it will set the cookie to the current playtime), and now I am out of ideas.
I am hoping to get an answer for this as I am sure this code could help others who've been trying to get some sort of resume audio function that isn't bulky or confusing to use. :)
I've been trying to find a solution for quite awhile and never have been this close. Thank you for reading. If you'd like the whole PHP function then I'll show that too but there's really nothing to see except two debug buttons (Reset and Alert cookie) and the audio tag with the id 'music_$song'.
Edit: Just to be clear, in the code, there are escapes before double quotes because the javascript is being returned in the PHP function.
Edit 2: Have now bolden this edit because it has been missed by some people. In addition I have added the PHP portion.
Last edit: I have now seemed to figure something out that got me closer to what I wish to achieve. I changed the above code to the following and it works flawless for me.
function playmusic($song, $resume=false, $loop=true)
{
global $baseurl, $loggeduser;
if ($resume == true)
{
$resume = "
<!--
<button onclick=\"resetplaytime();\" type=\"button\">Reset</button>
<button onclick=\"alertplaytime();\" type=\"button\">Alert Time</button>
<button onclick=\"settimecookie();\" type=\"button\">Start Cookie tracking</button>
-->
<script type=\"text/javascript\">
function getcookie(c_name)
{
var i,x,y,ARRcookies=document.cookie.split(\";\");
for (i=0;i<ARRcookies.length;i++)
{
x=ARRcookies[i].substr(0,ARRcookies[i].indexOf(\"=\"));
y=ARRcookies[i].substr(ARRcookies[i].indexOf(\"=\")+1);
x=x.replace(/^\s+|\s+$/g,\"\");
if (x==c_name)
{
return unescape(y);
}
}
}
function settimecookie()
{
var curmusic_$song = document.getElementById(\"music_$song\");
var playtime = curmusic_$song.currentTime;
if (playtime != null && playtime != \"\")
{
document.cookie = \"musicplaytime_$song=\" + playtime;
}
setTimeout(\"settimecookie()\", 50);
}
function resumeplaytime()
{
var curmusic_$song = document.getElementById(\"music_$song\");
var musictime = getcookie(\"musicplaytime_$song\");
if (musictime != null && musictime != \"\")
{
curmusic_$song.currentTime = musictime;
}
curmusic_$song.play();
settimecookie();
}
window.onload=resumeplaytime;
function alertplaytime()
{
var musictime = getcookie(\"musicplaytime_$song\");
alert(musictime);
}
function resetplaytime()
{
var curmusic_$song = document.getElementById(\"music_$song\");
curmusic_$song.currentTime=0;
}
</script>";
}
else
{
$autoplay = "autoplay=\"true\"";
}
if ($loop == true)
{
$songloop = " loop=\"true\"";
}
if ($loggeduser['mutemusic'] == 0)
{
return "
</table>
$resume
<audio id=\"music_$song\" $autoplay$songloop preload=\"true\">
<source src=\"$baseurl/boardfiles/effects/$song.ogg\" type=\"audio/ogg\" />
<source src=\"$baseurl/boardfiles/effects/$song.mp3\" type=\"audio/mp3\" />
</audio>
<table class=\"brdr\" cellpadding=\"0\">";
}
}
It seems to work perfectly now. I changed a few things and now works as I want it to. Thanks for the help! :)
It looks like you try to execute document.getElementById("music_$song") before the DOM is available. Use an onload handler for that.
Yet, I could not find any call to alert() or alertplaytime() that would let that wait - especially not in a loop as you have described.
Also, the line window.onload=settimecookie(); is buggy. settimecookie does not return an event handler function when beeing executed.

Detect page refresh or new load using PHP or Javascript

How to detect tab close in browsers using PHP or Javascript. In other words, How to find if page is refreshed or opened in new tab. I am concerned about tab, not browser.
You can have a listener for the window.onbeforeunload event. You won't be able to detect if the tab is closed from JavaScript, though.
Actually Javascript can tell you if a Tab is going to be closed. Two different methods need to be used (one for IE and one for everyone else).
I wrote a Javascript process to do just what you are asking. Pre-requisites for the process is jQuery and one plugin (livequery - because some of the HTML is dynamically generated after page load). Anyway, here is the js file that does all this (checkclosing.js):
// Global Var
var bodyclicked = false;
var datachanged = false;
var nodirtycheck = false;
// Start the engines :)
$(document).ready(function () {
init();
});
function init() {
bindEvents();
}
function bindEvents() {
// Bind the onClick event for the DOM body
$(document).livequery(function () {
bodyclicked = true;
});
// Bind our event handlers for the change and reset events
$(':input').not('.excludeFromDirtyCheck').bind('change', function () {
if ($(this).hasClass('dataLoader')) {
if (!datachanged) {
return;
}
}
datachanged = true;
$(".hidDataChanged").val("True");
});
$(':reset,:submit').bind('click', function () {
// .NET renders some ASP Buttons as Submit and Reset types
if ($(this).hasClass('notSubmit')) {
return;
}
if ($(this).hasClass('notReset')) {
return;
}
datachanged = false;
$(".hidDataChanged").val("False");
});
// Must have the livequery plugin referenced for this to work
$('.resetchangedform').livequery('click', function (event) {
//alert("resetchanged"); // FIXME
datachanged = false;
// Set our hidden input (on the Administration Master page)
$(".hidDataChanged").val("False");
});
// Must have the livequery plugin referenced for this to work
$('.setchangedform').livequery('click', function (event) {
//alert("setchanged"); // FIXME
datachanged = true;
// Set our hidden input (on the Administration Master page)
$(".hidDataChanged").val("True");
});
// Must have the livequery plugin referenced for this to work
$('.excludeFromDirtyCheck').livequery('click', function (event) {
nodirtycheck = true;
});
// Must have the livequery plugin referenced for this to work
$('.notSubmit').livequery('click', function (event) {
nodirtycheck = true;
});
// Must have the livequery plugin referenced for this to work
$('.dataReloader').livequery('change', function (event) {
nodirtycheck = true;
});
window.onbeforeunload = function () {
//alert("datachanged = " + datachanged + " | nodirtycheck = " + nodirtycheck + " | hidDataChanged = " + $(".hidDataChanged").val());
// Check the hidden textbox
if ($(".hidDataChanged").val() == "True") {
datachanged = true;
}
if (nodirtycheck) {
nodirtycheck = false;
}
else {
if (navigator.appName == "Microsoft Internet Explorer") {
// IE
if (bodyclicked) {
if (datachanged) {
return "You may have unsaved changes...";
}
}
else {
bodyclicked = false;
// Do Nothing
}
}
else {
// Not IE
if (datachanged) {
return "You may have unsaved changes...";
}
else {
// Do Nothing
}
} //if (navigator.appName == "Microsoft Internet Explorer") {
} //window.onbeforeunload = function () {
} // if (nodirtycheck) {
}
Then just include a reference to this file on any page you want to check for a tab close on:
This was built to help prevent users from navigating away from pages with unsaved changes to form values. Yes, I know that most of the time, it is bad practice to prevent the user from closing a tab or navigating away, but in this case - the users requested it and this is an internal application that is not for public consumption.
Any controls that you don't want to be checked for changes prior to letting the user close the tab or navigate away would just be given a class name of excludeFromDirtyCheck.
This may be more than you need, but you can strip off the parts that aren't useful. The basic premise is the same.

show hidden div section based on if statement

I have a few hidden divs on page like this
<div class="form" id="scheduler" style="display: none;">
<div class="form" id="test" style="display: none;">
<div class="form" id="super" style="display: none;">
I would like a jscript which can be called to show these hidden divs based on criteria like this
<?php
if ($_GET['id'] == 'scheduler') {
call jscript function (show div id:scheduler in this case)
}
else if ($_GET['id'] == 'test') {
call jscript function (show div id:test in this case)
}
else if ($_GET['id'] == 'super') {
call jscript function (show div id:super in this case)
}
?>
thanks.
you cannot call javascript function from PHP, PHP is server side based and stands for Preprocesing Hypertext while Javascript is browser based.
You could use:
<?php
if ($_GET['id'] == 'scheduler') {
$showdiv = 'scheduler';
}
else if ($_GET['id'] == 'test') {
$showdiv = 'test';
}
else if ($_GET['id'] == 'super') {
$showdiv = 'super';
}
echo "<script type=\"text/javascript\">document.getElementById('".$showdiv."').style.display = 'block';</script>";
?>
but that should be at bottom of the page, after those divs are loaded.
<script type='text/javascript'>
function showDivById(id){
document.getElementById(id).visible = true;
}
<?php
$divs = array('scheduler','test','super');
if (array_seach($_GET['id'], $divs)!==false)
echo "showDivById({$_GET['id']})";
?>
</script>
Note that php code is within the <script>
Why don't you write your function to accept the id param of the query string?
<script>thefunction($get);</script>
This way you can save on if logic, and develop a more abstract function. It's less code, and easier to manage.
First of all. I would use jquery to show/hide divs...
but my concept would be a bit different then above,
<?php
if($_GET['id']){
echo '<script type="text/javascript">$(\'#'.$_GET['id'].'\').show();</script>';
}
?>
Hope that you got my idea, it's clean and pretty dynamic :)
Even though you've accepted an answer, another option would be to use only JavaScript with the aid of some JS to easily retrieve values from the query string.
function $get(variable) {
var query = window.location.search.substring(1);
var vars = query.split('&');
for (var i = 0; i < vars.length; i++) {
var pair = vars[i].split('=');
if (pair[0] == variable) {
return pair[1];
}
}
}
var qs_id = $get('id');
if (['scheduler', 'test', 'super'].indexOf(qs_id) >= 0) {
document.getElementById(qs_id).style.display = 'block';
}
Demo: jsfiddle.net/Marcel/L69xt/show

Categories