I was following a tutorial on YouTube about how to display a popup box after the click of a button. It was fairly simple but now I want to twist things a little bit. I want to display the markup inside a PHP IF function.
I believe that creating a JavaScript function would be the road to follow but I am not proficient in JavaScript/jQuery as I am only starting with it now.
I want to display the following markup should my PHP IF function equate to TRUE
<div id="popup-box" class="popup-position">
<div class="popup-wrapper"> <!-- move away from screen and center popup -->
<div class="container"> <!-- backgorund of pop up -->
<h2>Pop box<h2>
<p>Close popup</p>
</div>
</div>
</div>
The following JavaScript function is used in the tutorial that I was following. It works perfectly when it is triggered by onClick.
<script>
function toggle_visibility(id) {
var e = document.getElementById(id);
if(e.style.display == 'block')
e.style.display = 'none';
else
e.style.display = 'block';
}
</script>
I have the following PHP script
function cart($userEmailAdd){
global $dbc; // database connection variable
/*
Verify if the product that is being added already exists in the cart_product table.
Should it exist in the cart then display popup box with an appropriate
message.
Otherwise, add the product to cart_product
*/
if(isset($_GET['cart'])){
$productID = $_GET['cart'];
$queryCheckCart = "SELECT * from cart_product WHERE emailOfCustomer = '$userEmailAdd' AND cpProductid = '$productID'";
$executeCheckCart = mysqli_query($dbc, $queryCheckCart) or die (mysqli_error($dbc));
if(mysqli_num_rows($executeCheckCart) > 0 ){
/* IF MYSQLI_NUM_ROWS is greater than zero then
it means that the product already exists in the cart_product table.
Then display following markup*/
?>
<div id="popup-box" class="popup-position">
<div class="popup-wrapper"> <!-- move away from screen and center popup -->
<div class="container"> <!-- backgorund of pop up -->
<h2>Pop box<h2>
<p>X</p>
</div>
</div>
</div> <!-- -->
<?php
} else {
$query = "INSERT INTO cart..." ;
// rest of script continues after this for insertion of the product
How do I go about using the same function or a similar one without using onClick to display the markup?
you can just add inline css display:block so that the popup is displayed by default when page load.
<div id="popup-box" style="display:block" class="popup-position">
and then edit the close button of the popup to tell him to call toglle_visibility() onclick
<p>X</p>
of course you will need yo put your toggle_visibility() function in a script tag (better before the closing body element)
<script>
function toggle_visibility(id) {
var e = document.getElementById(id);
if(e.style.display == 'block')
e.style.display = 'none';
else
e.style.display = 'block';
}
</script>
You can do something similar to this:
function cart($userEmailAdd){
global $dbc; // database connection variable
/*
Verify if the product that is being added already exists in the cart_product table.
Should it exist in the cart then display popup box with an appropriate
message.
Otherwise, add the product to cart_product
*/
if(isset($_GET['cart'])){
$productID = $_GET['cart'];
$queryCheckCart = "SELECT * from cart_product WHERE emailOfCustomer = '$userEmailAdd' AND cpProductid = '$productID'";
$executeCheckCart = mysqli_query($dbc, $queryCheckCart) or die (mysqli_error($dbc));
if(mysqli_num_rows($executeCheckCart) > 0 ){
/* IF MYSQLI_NUM_ROWS is greater than zero then
it means that the product already exists in the cart_product table.
Then display following markup*/
?>
<script>
$(document).ready(function(){
toggle_visibility('popup-box');
});
</script>
<div id="popup-box" class="popup-position">
<div class="popup-wrapper"> <!-- move away from screen and center popup -->
<div class="container"> <!-- backgorund of pop up -->
<h2>Pop box<h2>
<p>X</p>
</div>
</div>
</div> <!-- -->
<?php
} else {
$query = "INSERT INTO cart..." ;
// rest of script continues after this for insertion of the product
All you have to do is to tell javascipt that it has to open popup. Here, I made Javascript run function toggle_visibility('popup-box'); after the document loads.
The popup div doesn't have to be inside php's IF statement. And instead of using $(document).ready(function(){ }); you can use onLoad="toggle_visibility('popup-box')" attribute in <body> element.
Instead of executing the html block within the php if clause, you could use a simple boolean variable to indicate whether or not to show the popup:
$showPopup = false;
if(mysqli_num_rows($executeCheckCart) > 0 ){
/* IF MYSQLI_NUM_ROWS is greater than zero then
it means that the product already exists in the cart_product table.
Then display following markup*/
$showPopup = true;
?>
<?php
} else {
Then in your html code you could show the popup based on what the $showPopup has been set to:
<div id="popup-box" <?php echo ($showPopup === false)? 'style="display:none"' : '' ?> class="popup-position">
</div>
Related
Having a very weird issue with a simple div visibility toggle script.
I'm just using javascript to switch a div between 'display: block' and 'display: none' to toggle its visibility. Very routine stuff.
And in general it works, but it always fails on the first click after a fresh page load. Then it works consistently from the second click onward.
No error output on console.
Relevant HTML:
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript" src="res/classes.js"></script>
<script type="text/javascript" src="res/util_c.js"></script>
<script type="text/javascript">
// load client prefs
var clientPrefs = new ClientPrefs();
</script>
</head>
<body>
<a id="join_show_publist" class="a_btn" onClick="javascript:joinPublistToggle()">View Public Matches</a><br />
<!-- list of public games -->
<div id="join_publist_container" class="ovr">
<table id="join_publist_listbox">
<tr id="join_publist_listbox_header">
<td>Table Name</td>
<td>Open</td> <!-- open seats remaining at table -->
</tr>
</table>
<div class="spacer"></div>
<div id="join_savePref_container">
<input id="join_savePref" type=checkbox onclick="javascript:clientPrefs.joinAlwaysShowPubToggle()" />
<span id="join_savePref_label" onclick="javascript:clientPrefs.joinAlwaysShowPubToggle()">Always show public tables list</span>
</div>
</div>
Relevant CSS:
div.ovr {
display: none;
}
...and finally in util_c.js:
// toggle visibility of public tables list
function joinPublistToggle() {
var listContainer = document.getElementById('join_publist_container');
if (listContainer.style.display == 'none') {
listContainer.style.display = 'block';
} else {
listContainer.style.display = 'none';
}
}
First click: nothing happens.
Second click: the DIV is shown
Third click: the DIV is re-hidden
etc..
If I put an alert(listContainer.style.display) into the joinPublistToggle function, the alert comes up empty with the first click, then shows 'none' with the second click.
But the CSS specifically sets the display style for that div as 'none' on load. And if I look at that div in the page inspector after a fresh page load the inspector specifically says the div's display property is set to none.
So the issue seems to be that javascript is reading that property as empty even though that property is set as 'none'.
Why would it do that?
style returns the inline style of the element, and your element doesn't have any, which is why listContainer.style.display returns an empty string and the condition fails.
It would work if you compared against 'block' instead but it's not really more reliable.
function joinPublistToggle() {
var listContainer = document.getElementById('join_publist_container');
if (listContainer.style.display == 'block') {
listContainer.style.display = 'none';
} else {
listContainer.style.display = 'block';
}
}
https://stackoverflow.com/questions/69213611/js-onclick-event-ignores-first-click-works-for-every-subsequent-click/69224191#
The other answers provide valid solutions, here is another using classes:
CSS:
div.hidden {
display: none;
}
HTML:
<div id="join_publist_container" class="ovr hidden">
(of course you can also just keep using ovr but I wasn't sure what that's for)
JS:
function joinPublistToggle() {
document.getElementById('join_publist_container').classList.toggle('hidden');
}
And in general it works, but it always fails on the first click after a fresh page load. Then it works consistently from the second click onward.
I am going to asume when you clicked the link, the checkbox and the table should go away. And when it is clicked again, the table and the checkbox should show. I modified your code and it works for me.
for your HTML:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<script type="text/javascript" src="classes.js"></script>
<script type="text/javascript" src="util_c.js"></script>
<script type="text/javascript">
// load client prefs
var clientPrefs = new ClientPrefs();
</script>
</head>
<body>
<a id="join_show_publist" class="a_btn" onClick="javascript:joinPublistToggle()">View Public Matches</a><br />
<!-- list of public games -->
<div id="join_publist_container" class="ovr">
<table id="join_publist_listbox">
<tr id="join_publist_listbox_header">
<td>Table Name</td>
<td>Open</td> <!-- open seats remaining at table -->
<td>Starts</td> <!-- time left until game starts (or "started" if underway) -->
<td>Timer</td> <!-- time limit for turns (or "none") -->
<td>Min</td> <!-- min players to start the round (or '--' if already underway) -->
<td>Late</td> <!-- whether late joiners are allowed at the table -->
<td>AI</td> <!-- whether there are any AI players at the table (and if so, how many)
also colour denotes difficulty: green-easy / yellow-med / red-hard -->
</tr>
<!-- Generate list via js. Clicking any list entry joins -->
</table>
<div class="spacer"></div>
<div id="join_savePref_container">
<input id="join_savePref" type=checkbox onclick="javascript:clientPrefs.joinAlwaysShowPubToggle()" />
<span id="join_savePref_label" onclick="javascript:clientPrefs.joinAlwaysShowPubToggle()">Always show public tables list</span>
</div>
</div>
Classes.js:
// ClientPrefs - client-side preferences
class ClientPrefs {
constructor() {
// JOIN GAME page settings
this.joinAlwaysShowPub = false;
}
joinAlwaysShowPub() { return joinAlwaysShowPub; }
joinAlwaysShowPubToggle() {
// toggle setting in memory
this.joinAlwaysShowPub = !this.joinAlwaysShowPub;
// update checkbox & label
document.getElementById('join_savePref').checked = this.joinAlwaysShowPub;
}
}
And finally your other script:
function joinPublistToggle() {
var listContainer = document.getElementById('join_publist_container');
if (listContainer.style.display == 'none') {
listContainer.style.display = 'block';
} else {
listContainer.style.display = 'none';
}
}
Here are few reasons why your code might not work:
I think the problem is that you mistyped joinPublistToggle() to joinShowPubList.
Your div has a value of nothing for the display property. So, when JS looks at your div, well, the div is not set to none or block, I don't know how to handle it. After you clicked the link a second time, it sets the display in your JS code. So, it knows how to handle it.
Maybe add an display property to your a tag and set it to block so JS know what the property of the style is.
<a id="join_show_publist" class="a_btn" onClick="javascript:joinPublistToggle()" style="display:block;">View Public Matches</a><br />
This doesn't really answer my question, but I've implemented a simple workaround by adding an OR statement into the JS function:
function joinPublistToggle() {
var listContainer = document.getElementById('join_publist_container');
if ( (listContainer.style.display == 'none') ||
(listContainer.style.display == '' ) ) {
listContainer.style.display = 'block';
} else {
listContainer.style.display = 'none';
}
}
This doesn't explain why it was behaving so odd, and it isn't a proper solution (as a proper solution would address the cause, not the symptom).
But it works.
I won't mark the post as solved just yet in case any wizards end up reading this and are able to explain why the problem occurred in the first place.
I am trying to display images from a database with a time delay between each image. The time delay is selectable from the user interface
and stored in seconds in the same record as the image. I aalready have the images displaying but I need to incororate the dynamic time delay.
The time delay is stored in a field named "TimeLapse". Below I have tried to used the content of "TimeLapse as $HoldTime each time
the while loop display a new image.
Image one has a TimeLapse of "5000".
Image two has a TimeLapse of "15000".
But it looks like it's only using the first TimeLapse of 5000 for both images."
Can anyone see how I can do this.
PHP CODE
while($row_fb = mysqli_fetch_array($fb)){ ?>
<?php $url = $ImagePath.''.$row_fb['SignageImageName'];
$HoldTime = $row_fb['TimeLapse']?>
<div class="outer">
<div class="banner-container">
<div id="wrapper">
<a><img src="/<?php echo $url;?>" class="responsive"/></a>
</div>
</div>
</div>
<?php
}
JAVASCRIPT
(function() {
var a = $('.outer').children();
var index = 0;
run()
function run() {
a.filter('.active').fadeOut(500).removeClass('active');
a.eq(index).fadeIn(500).addClass('active');
index = (index + 1) % a.length;
setTimeout(run, <?php echo $HoldTime;?>);
}
})();
I would put the delay time into an HTML data- attribute and read it in the JavaScript to set the delay. (Note use of alternative syntax and short echo tags, this makes your PHP code more readable when mixed with HTML.)
<?php while($row = $fb->fetch_array()): ?>
<div class="outer">
<div class="banner-container" data-delay-time="<?=$row['TimeLapse']?>">
<div id="wrapper">
<a>
<img src="/<?=$ImagePath . $row['SignageImageName']?>" class="responsive"/>
</a>
</div>
</div>
</div>
<?php endwhile ?>
The JS has been cleaned up to eliminate any dependency on variables from outside the function. Instead it just looks for the active banner's next sibling, looping to the beginning if it doesn't have one. Some test HTML is included for a runnable example.
(function() {
$("div.outer div.banner-container").hide();
run();
function run() {
// get a list of all the banners
var banners = $("div.outer div.banner-container");
if (!banners.length) {
return;
}
// active is the one with "active" class, or the first one
var active = banners.filter(".active").first();
if (!active.length) {
active = banners.first();
}
// get the next one or loop to the beginning again
var next = active.next("div.banner-container");
if (!next.length) {
next = banners.first();
}
active.fadeOut(500).removeClass("active");
next.fadeIn(500).addClass("active");
// get the delay time from the data-delay-time attribute
setTimeout(run, next.data("delayTime"));
}
})();
.active {
background: blue;
color: white
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="outer">
<div class="banner-container" data-delay-time="1000">foo</div>
<div class="banner-container" data-delay-time="2000">bar</div>
<div class="banner-container" data-delay-time="6000">baz</div>
<div class="banner-container" data-delay-time="10000">boo</div>
</div>
I have a page that shows rows from database and every row has a hidden form to edit it . i wanted to show the form of the choosed row on button click with javascript, i tried all possibilities i know and i searched for (like array for getElementbyID, onclick inside for loop ... etc ) .
In other attempts : it worked but every button displayed only one form, either the first or the last, which is not the target .
Here's the important from my code :
while($row_publications=$result_publications->fetch_assoc()){
$counter++ ;
echo "<h3>".$counter.") ".$row_publications['title']." :</h3><br/>";
echo "<button id='display_button_".$counter."' onclick=\'display_edit_form(".$counter.");\'>Edit</button>
<div id='edit_form_".$counter."' style='display:none;'>";
//the form
echo "</div>";
//Here's my last try in javascript i tested it manually for 2 rows :
<script>
var i = 0;
var counter= <?php echo $counter; ?> ;
var element = ["empty","edit_form_1","edit_form_2"];
var display_buttons = ["empty","display_button_1","display_button_2"];
for(i=1;i<=counter;i++){
document.getElementById(display_buttons[i]).onclick= function myfunction(){ display_edit_form(i); };
}
//I tried also another variable v=i and same undefined parameter problem on call
function display_edit_form(i){
alert("i="+element[i]); // this alerts : i=undefined
if (document.getElementById(element[i]).style.display === "none") {
document.getElementById(element[i]).style.display = "block";
} else {
document.getElementById(element[i]).style.display = "none";
}
}
</script>
There is no need to use ID attributes in a loop - it gets overly complicated. Instead you can use sibling selectors - once you have identified the relationship between elements (in this case between the button and the DIV element - relation is essentially nextSibling ) you can invoke it with quite simple syntax.
The below creates a mockup of "the important part of your code" - the loop in this case just generates 10 elements with hidden forms. Notice that all of the ID attributes have been removed and the inline event handler has been put in the HEAD section as an external event listener.
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8' />
<title>Targeting sibling element</title>
<script>
/*
wait for the DOM to load and then find all buttons
that are to be used for triggering the display of the hidden
forms.
*/
document.addEventListener('DOMContentLoaded',()=>{
Array.from( document.querySelectorAll('button.edit') ).forEach( bttn=>{
/*
iterate through the nodelist collection and assign a `click` event handler
to each button.
*/
bttn.addEventListener('click',function(e){
let div=this.nextElementSibling;
div.style.display = div.style.display=='block' ? 'none' : 'block';
})
});
});
</script>
</head>
<body>
<?php
for( $i=1; $i <= 10; $i++ ){
printf(
'<h3>Counter: %1$d) Publication Title: %1$d :</h3>
<br />
<button class="edit">Edit</button>
<div style="display:none;">
<form>
<!-- other content -->
<h1>Form #%1$d</h1>
</form>
</div>',
$i
);
}
?>
</body>
</html>
document.addEventListener('DOMContentLoaded',()=>{
Array.from( document.querySelectorAll('button.edit') ).forEach( bttn=>{
bttn.addEventListener('click',function(e){
let div=this.nextElementSibling;
div.style.display = div.style.display=='block' ? 'none' : 'block';
})
});
});
<h3>Counter: 1) Publication Title: 1 :</h3>
<br />
<button class="edit">Edit</button>
<div style="display:none;">
<form>
<!-- other content -->
<h1>Form #1</h1>
</form>
</div>
<h3>Counter: 2) Publication Title: 2 :</h3>
<br />
<button class="edit">Edit</button>
<div style="display:none;">
<form>
<!-- other content -->
<h1>Form #2</h1>
</form>
</div>
Given Script load data from specific div of external source on click. Now trying to add div class when loading content like image and text. I mean when contents loads new classes will auto added with <div class="images"> img</div> and <div class="summery"> text text text</div>
HTML:
<button class='btn'/>
<div id="load-here"></div> <!-- Load Here -->
</body>
Script:
$(function() {
var page = null;
var counter = 0;
function getNext() {
// Grab the next element from the array of date-outer divs and copy it to the .content div
if (counter >= page.length)
return;
var elm = $(page[counter]).clone();
elm.find('script').remove(); // Remove script tags in the div
elm.appendTo('#load-here');
counter++;
}
$('button.btn').click(function(e) {
if (page === null) {
page = false; // Prevents the request from being made twice
$.get('http://test-html-site.blogspot.com/search/label/', function(data) {
page = $(data).find('article.post.hentry');
getNext();
});
} else if (page !== false) {
getNext();
}
});
});
HTML Structure of external site: Given script load .date-outer per click. Means it load data form external site/link on click.
<body>
<div class="blog-posts hfeed">
<div class="date-outer">
Contecnt 1: img, text </div>
<div class="date-outer">
Contecnt 2: img, text </div>
<div class="date-outer">
Contecnt 3: img, text </div>
</div>
</body>
My question is when data loading, want to add custom class to image and text using given script. This is the example site.
I am using jQuery to hide / show sections of content on a page. On one page, I have two such sections. Right now the page loads with both hidden. I need the page to load with the first div visible and the second one hidden.
Here is my javascript:
function a2012() {
var ele = document.getElementById("toggleArch12");
var text = document.getElementById("displayArch12");
if(ele.style.display == "block") {
ele.style.display = "none";
text.innerHTML = "2012 Newsletter Archive";
}
else {
ele.style.display = "block";
text.innerHTML = "Hide Archive";
}
}
function a2011() {
var ele = document.getElementById("toggleArch11");
var text = document.getElementById("displayArch11");
if(ele.style.display == "block") {
ele.style.display = "none";
text.innerHTML = "2011 Newsletter Archive";
}
else {
ele.style.display = "block";
text.innerHTML = "Hide Archive";
}
}
and the HTML to set up the DIVs and their toggle links:
<a id="displayArch12" href="javascript:a2012();">2012 Newsletter Archive</a>
<div id="toggleArch12" style="display:none">content goes here</div>
<a id="displayArch11" href="javascript:a2011();">2011 Newsletter Archive</a>
<div id="toggleArch11" style="display:none">content goes here</div>
I tried changing style="display:none" for the first div to style="display:visible" and while it does cause the page to load with the contents visible, the toggle link still shows the "click to open" text (in this case "2012 Newsletter Archive").
I need the first div to load visible and the correct toggle text (Hide Archive) to show as well. Any ideas?
If you want to use jQuery (which you are not from the code you've posted), you could write it like this:
$("#displayArch11").click(function(e) {
var $display = $(this)
$display.next().toggle(function() {
$display.html($display.html() == "2011 Newsletter Archive" ? "Hide Archive" : "2011 Newsletter Archive");
});
e.preventDefault();
});
$("#displayArch12").click(function(e) {
var $display = $(this)
$display.next().toggle(function() {
$display.html($display.html() == "2012 Newsletter Archive" ? "Hide Archive" : "2012 Newsletter Archive");
});
e.preventDefault();
});
and the HTML like this
<a id="displayArch12" href="#">2012 Newsletter Archive</a>
<div id="toggleArch12" style="display:none">content goes here</div>
<a id="displayArch11" href="#">2011 Newsletter Archive</a>
<div id="toggleArch11" style="display:none">content goes here</div>
This is easier if you use jQuery, but I think simply setting the correct default html should achieve your goal.
<a id="displayArch12" href="javascript:a2012();">Hide Archive</a>
<div id="toggleArch12" style="display:block">content goes here</div>
Change the inline script:
<div id="toggleArch12" style="display:block">content goes here</div>
First, if you want one of the divs to be visible, just don't specify the display property. They are visible by default. Though the value you are looking for with a div is display:block;
I would use a div instead of a link for your toggling needs.
<div id="displayArch12" class="toggleDiv">
2012 Newsletter Archive
<div id="toggleArch12" style="display:block;">Content Here</div>
</div>
<div id="displayArch11" class="toggleDiv">
2011 Newsletter Archive
<div id="toggleArch11" style="display:none;">Content Here</div>
</div>
Then you need some real jQuery to toggle them properly.
$(function() {
$(".toggleDiv").click(function () {
$("div:first-child", this).toggle();
});
});
That should work for you. And of course don't forget to include the jQuery library itself. The easiest way is to use the Google API link.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>