echo "<div id=\"userinfo\"><p><strong>$username</strong></p><p>Bids: <strong>$bids</strong></div>
<script>
var usn = document.getElementById('userstuff');
menu = document.getElementById('userinfo');
if (usn)
{
usn.addEventListener('click',toggle_menu);
}
function toggle_menu()
{
alert('clicked');
if (menu.style.display == '')
{
menu.style.display='block';
}
else if (menu.style.display == 'block')
{
menu.style.display='';
}
}
</script>";
This code works on the first click. By default, the display value in menu is set to 'none'. The first click, the user is alerted 'clicked' and the menu becomes visible. However, on more clicks, the user is alerted 'clicked' but the menu does not become invisible and the 'hidden' alert does not show.
Remember that = is for assignment, use == for comparison. Another problem is that checking menu.style.display only checks inline styles of the node, such as:
<div style="display: none"></div>
Thus if the style is not set comparison will fail. '' comparison instead of 'none' works because by default the properties are empty strings if not set, seen here.
A few other recommendations: always declare your variables with var to prevent global scope pollution with many global variables. Here's the final JavaScript:
var usn = document.getElementById('userstuff'),
menu = document.getElementById('userinfo');
if (usn) {
usn.addEventListener('click', toggle_menu);
}
function toggle_menu() {
alert('clicked');
if(menu.style.display == '' || menu.style.display == 'none') {
menu.style.display = 'block';
return;
} else if (menu.style.display == 'block') {
menu.style.display = 'none';
return;
}
}
Related
I have various input elements which control the "hidden" state of various dependent divs.
The type of input varies, and the value which the input must equal (to reveal the div) also varies. I have used php to write javascript (jQuery) depending on these factors, by using the general piece of code:
php
$remove .=" $('#".$id."').removeClass('hide');";
$add .="$('#".$id."').addClass('hide');";
...
$jquery ="
$(\"input[name$='$name."']\").change(function(){
if(this.value == '".$key_val."') {
".$remove."
} else {
".$add."
}
}).trigger('change');
";
Note: the $remove and $add variables are built using concatenation and loops as there may be several hidden elements which need to be hidden or revealed (hence the .=)
This generally results in a piece of code on page (actual code) such as:
jQuery
$(document).ready(function(){
$("input[name$='q_32']").change(function(){
if(this.value == 'Yes') {
$('#qu_33').removeClass('hide');
} else {
$('#qu_33').addClass('hide');
}
}).trigger('change');
$("input[name$='q_32']").change(function(){
if(this.value == 'No') {
$('#qu_34').removeClass('hide');
} else {
$('#qu_34').addClass('hide');
}
}).trigger('change');
});
On the page this works well: when the radio button in question (input name q_32) is changed, the corresponding element is hidden or revealed.
The .trigger('change'); is there because I want the divs to be hidden or revealed on page load having set the checked state server side.
The following is the HTML is how the page now loads:
HTML
<span>Yes</span>
<input type="radio" id="q_32_Yes" value="Yes" name="q_32" checked="">
<span>No</span>
<input type="radio" id="q_32_No" value="No" name="q_32">
<div id="qu_33" class="hide">...</div>
<div id="qu_34" class="">...</div>
i.e. the radio button is loading in the checked state for Yes, but the incorrect div is being revealed - so it is triggering, however it seems that the value is being read wrong.
The script should be
$(document).ready(function () {
$("input[name$='q_32']").change(function () {
if (this.value == 'Yes') {
$('#qu_33').removeClass('hide');
} else {
$('#qu_33').addClass('hide');
}
});
$("input[name$='q_32']").change(function () {
if (this.value == 'No') {
$('#qu_34').removeClass('hide');
} else {
$('#qu_34').addClass('hide');
}
});
$("input[name$='q_32']").filter(':checked').change()
});
Demo: Fiddle
a more correct script will be
$(document).ready(function () {
$("input[name$='q_32']").change(function () {
if (this.value == 'Yes') {
$('#qu_33').removeClass('hide');
$('#qu_34').addClass('hide');
} else {
$('#qu_33').addClass('hide');
$('#qu_34').removeClass('hide');
}
}).filter(':checked').change();
});
Demo: Fiddle
If you have more instances of the same code then try this
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';
}
}
}
}
I have a bunch of items setup with <div id="first" class="source">
I'm in Google Chrome, and when page loads it hides those items when I click the OnClick button it will un hide them, but I'm not able to click it again and make it hide.
HTML
<body onload="setup();">
<a href="#first" onClick="shoh('first');" >
JS:
function setup() {
foo = document.getElementById('first');
foo = document.getElementsByClassName('source');
for (c=0; c<foo.length; c++) {
foo[c].style.display='none'
}
}
function shoh(id) {
if (document.getElementById(id).style.display = 'none'){
var divs = document.getElementById(id);
for(var i=0; i<divs.length; i++) {
divs[i].style.display='block'
}
} else {
cow = document.getElementById(id);
for(a=0; a<cow.length; a++) {
cow[a].style.display='none'
}
}
}
Your conditional isn't doing a comparison. You need to change
if (document.getElementById(id).style.display = 'none'){
to
if (document.getElementById(id).style.display == 'none'){
You have a couple of issue here:
If you compare two variables you need to use ==, so therefore it should be:
document.getElementById(id).style.display == 'none'
Also, you are using getElementById, which returns a single node, not an array. So therefore you should not loop over the returned value:
var div = document.getElementById(id);
div.style.display='block';
So in the end, it should look like this:
function shoh(id) {
if (document.getElementById(id).style.display == 'none'){
var div = document.getElementById(id);
div.style.display='block';
} else {
cow = document.getElementById(id);
cow.style.display='none';
}
}
I have used this function to call the following page depending on the chosen option.
The First IF will direct me to the Monthly report while the second IF will direct me to the Daily report
<script type="text/javascript">
function ActionDeterminator()
{
var monthly = document.myform.duration.options[0].value;
var daily = document.myform.duration.options[1].value;
if (monthly == 0){
document.myform.action = 'month.php';
}
if (daily == 1) {
document.myform.action = 'day.php';
}
}
</script>
I have also another function which will execute a job depending on the option. The first IF will convert my report to excel doc while the second IF will direct me to view page to print.
<script type="text/javascript">
function ActionDeterminator()
{
if(document.myform.group[0].checked == true) {
document.myform.action = 'excel.php';
}
if(document.myform.group[1].checked == true) {
document.myform.action = 'view.php';
}
return true;
}
</script>
The Problem:
the problem is that it does not direct me to the correct page (whether monthly or daily)... it only directs me to view page or exporting to excel. Could anyone teach me the correct way to do this function?
Also, I want to ask the correct javascript for combo box.
What you'll want to do is get all the form elements into an array, loop, and evaluate for checked equals true
For example:
var elems = document.getElementsByName('group');
for (var i=0; i<elems.length; i++) {
if (elems.item(i).checked == true) {
break;
}
}
switch (i) {
case 0:
//action = 'excel.php';
break
//case etc...
}
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