Hide div content permanently - javascript

I want when the user click on submit button the content disappear (random text 3) until the user logs off. The JS works fine but, if I refresh the page, the content appears. Can anyone help me achieve this or can anyone convert my code to PHP so that I can use a session variable to achieve this?
<style type="text/css">
div.something{
/*random code;/*
}
</style>
<script type="text/javascript">
function hideSomething(){
document.getElementsByClassName("something")[2].style.display = "none";
}
</script>
<div class="something">random text 1</div>
<div class="something">random text 2</div>
<div class="something">random text 3</div><br />
<input type="submit" value="Disappear" onclick="hideSomething()" />

well the professional way is to record it on cookie or store in database with user information like IP or you can use rough way to just forward it to another page where that div not appear thou some dont allow cookies to store let me know which one you like and i will fill my answer with it sample

Use a cookie and store the status of the div there.
You can easily read and write a cookie using javascript.
A nice tutorial can be found here: http://www.w3schools.com/js/js_cookies.asp.
For example, in the hideSomething() function do the following:
document.cookie="display_div=true";
Then, when the page is loaded, call a javascript function that shows or hide the div based on the value of the cookie:
if(cookie_value == "true")
//Hide your div
else
//Show your div.
end

So first we create a form with a hidden text box, once user click on button Close Attendance the value of hidden textbox is submited and a session variable is created:
if(isset($_POST['hidden'])){
$_SESSION['closed'] = TRUE;
}
Then we check is session is set, if yes display attendance close, if not display content.
<?php if(isset($_SESSION['closed'])){
echo "attendance closed.";
}
else {
echo "<form name='test' action='attendance.php' method='post'>
<input type='hidden' name='hidden'/>
<button> Close Attendance </button>
</form>";
}
?>

try the following code, it should give you a very clear glimpse on how to do it.
<!DOCTYPE html>
<html>
<head>
<title>ZUUS: Ironman</title>
</head>
<script type="text/javascript">
function hideSomething()
{
document.cookie="hide_div=true";
myFunction();
}
function myFunction()
{
var cookie_value = getCookie("hide_div");
alert(cookie_value);
if(cookie_value == "true")
document.getElementById("test_div").style.display = "none";
}
function getCookie(cname)
{
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++)
{
var c = ca[i].trim();
if (c.indexOf(name)==0) return c.substring(name.length,c.length);
}
return "";
}
</script>
<body onload="myFunction();">
<div id="test_div" style="background-color: blue;" onclick="hideSomething();">
this is a test
</div>
</body>
</html>

Related

PHP, JS - Documenting and saving DATE/TIME to re-appear after browser closed

I currently have a sitation where I can click on an image and it will return a new image, and in the previous grid-item, it will return the day and time I clicked it.
What I want is to have this BUT where I also can see the updated image and clicked time after closing and re-opening the browser. - What is the easiest / quickest way to achieve this?
I feel like adding to my database would be a way forward, but if that is what I would need to do, how would I go about storing and out-putting the time based on the time I click?
(This is not intended to be a live site, or for others to see or use, so local quick-fixes are viable).
foreach ($flavours as $key => $flavour) {
echo "<div class='grid-container'>";
echo "<div class='item7'><p id='p3'>Sylus: </p></div>";
echo "<div class='item8'><img src='htts://i.i.com/k.jpg' onclick='cS(this)' /></div>";
echo "</div>";
}
function cS(element) {
if (element.src == "htts://i.i.com/k.jpg")
{
element.src = "http://i.i.com/v.jpg";
var d = moment().format('dddd HH:mm');
element.parentElement.previousElementSibling.firstChild.innerHTML = "Sylus: " + d;
}
else
{
element.src = "htts://i.i.com/k.jpg";
element.parentElement.previousElementSibling.firstChild.innerHTML = "Sylus: ";
}
}
Try this example using localStorage. This will find the <p> tag elements within the body, and then uses each element to get the id for reference.
I tried using a fiddle here, but the site has a security complaint with the localStorage.
Copy/paste this code to a file to give it a try. Note that you will likely need to update the moment.js reference in this code to match your file path.
<!doctype html>
<html>
<head>
<title>localStorage example</title>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script src="moment.js"></script>
</head>
<body>
<div class='grid-container'>
<div class='item7'><p id='p0'>Sylus: </p></div>
<div class='item8'><img src='htts://i.i.com/k.jpg' onclick='cS(this)' /></div>
</div>
<div class='grid-container'>
<div class='item7'><p id='p1'>Sylus: </p></div>
<div class='item8'><img src='htts://i.i.com/k.jpg' onclick='cS(this)' /></div>
</div>
<script>
function cS(element) {
var pTag = element.parentElement.previousElementSibling.firstChild;
if (element.src == "htts://i.i.com/k.jpg")
{
element.src = "http://i.i.com/v.jpg";
var d = moment().format('dddd HH:mm');
var pText = 'Sylus: ' + d;
pTag.innertHTML = pText;
// Set (save) a reference to browser localStorage
localStorage.setItem(pTag.id, pText);
}
else
{
element.src = "htts://i.i.com/k.jpg";
pTag.innerHTML = "Sylus: ";
// Remove the stored reference. (delete this if not needed)
localStorage.removeItem(pTag.id);
}
}
$(document).ready(function() {
pElements = $('body').find('p').each(function(index, element) {
// Get the localStorage items. The retrieved <p> elements,
// we use their id value to reference the key in storage.
storageItem = localStorage.getItem(element.id);
if (storageItem) {
$('#' + element.id).text(storageItem);
}
});
});
</script>
</body>
</html>
After clicking an image (will need to replace with something real), open the browser's web inspector interface, click the Storage tab, and then expand the Local Storage in the list (see image below), and choose the file being tested.
There will be key/value pairs displayed. The keys are references to the <p> tag id's, and the value will have a label-date strings such as Sylus: Wednesday 22:28.
Once you see an entry, or two, being set to the storage, close and then reopen the browser tab. The <p> elements that had dates should be reloaded with their values from the storage.
The browser's Local Storage area should be similar to the image below:
save it to local storage, or a cookie with the exp. date too far in the future

Set to true state a checkbox in a different page(javascript)

Here's the Script.
javascript
function linkPageContact(clicked_id){
if(clicked_id === 'website-design-check'){
$('#website-design').attr('checked',true);
window.location.href = "/contact";
}
}
}
I want to check my checkboxes when I click the button with an id=website-design-check.
Here is my HTML.
first.html
<a href="/contact" target="_blank">
<button type="button" class="btn btn-success btn-block" id="website-design-check" onclick="linkPageContact(this.id)">Appointment</button>
</a>
Here's the second HTML file where checkbox is.
second.html
<input type="checkbox" aria-label="Checkbox for following text input" id="website-design" name="website-design">
Now how can I achieve what I want base on the description given above. Can anyone help me out guys please. I'm stuck here for an hour. I can't get any reference about getting a checkbox state from another page.
To do this, you can modify your button link and add in additional parameters that you can then process on the next page.
The code for the different pages would be like:
Edit: I changed it to jQuery, it should work now.
Script
function linkPageContact(clicked_id){
if(clicked_id === 'website-design-check'){
window.location.href = "second.html?chk=1";
}
}
second page
<input type="checkbox" aria-label="Checkbox for following text input" id="website-design" name="website-design">
<script type="text/javascript">
var url = window.location.href.split("?");
if(url[1].toLowerCase().includes("chk=1")){
$('#website-design').attr('checked',true);
}
</script>
since your checkbox is in another html page, so it's totally normal that you can't get access to it from your first html page!
what I can offer u is using the localstorage to keep the id and then use it in your second page to check if it's the ID that u want or not.
so change your function to this :
function linkPageContact(clicked_id){
localStorage.setItem("chkId", "clicked_id");
window.location.href = "/contact";
}
then in your second page in page load event do this :
$(document).ready(function() {
var chkid = localStorage.getItem("chkId");
if(chkid === 'website-design-check'){
$('#website-design').attr('checked',true);
});
You can't handle to other sites via JavaScript or jQuery directly. But there's another way. You can use the GET method to achive this.
First you need to add to the link an attribute like this in your first.html:
/contact?checkbox=true
You can change the link as you want with JavaScript.
Now it will refer to the same page but it can be now different. After that you can receive the parameter with this function on the second.html.
function findGetParameter(parameterName) {
var result = null,
tmp = [];
var items = location.search.substr(1).split("&");
for (var index = 0; index < items.length; index++) {
tmp = items[index].split("=");
if (tmp[0] === parameterName) result = decodeURIComponent(tmp[1]);
}
return result;
}
I got it from this post thanks to Bakudan.
EDIT:
So here is an short theory.
When the user clicks the button on the first page, then you change the link from /contact to /contact?checkbox=true. When the user get forwarded to second.html then you change the checkbox depending on the value, which you got from the function findGetParameter('checkbox').
As all have mentioned you need to use session/query string to pass any variable/values to another page.
One click of the first button [first page] add query string parameter - http://example.com?chkboxClicked=true
<a href="secondpage.html?chkboxClicked=true>
<button>test button</button>
</a>
In the second page- check for the query string value, if present make the checkbox property to true.
In second page-
$(document).ready(function(){
if(window.location.href.contains('chkboxClicked=true')
{
$('#idOfCheckbox').prop('checked','checked');
}
})
Add it and try, it will work.
Communicating from one html file to another html file
You can solve these issue in different approaches
using localStorage
using the query parameters
Database or session to hold the data.
In your case if your application is not supporting IE lower versions localStorage will be the simple and best solution.
<!doctype html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<a href="contact.html" target="_blank">
<button type="button" class="btn btn-success btn-block" id="website-design-check" onclick="linkPageContact(this.id)">Appointment</button>
</a>
<script>
function linkPageContact(clicked_id) {
localStorage.setItem("chkId", clicked_id);
}
</script>
</body>
</html>
<!doctype html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<input type="checkbox" aria-label="Checkbox for following text input" id="website-design" name="website-design">
<script>
$(document).ready(function () {
var chkid = localStorage.getItem("chkId");
if (chkid === 'website-design-check') {
$('#website-design').attr('checked', true);
}
});
</script>
</body>
</html>

how to get textarea input from another HTML page

In a.html:
I have a textarea that is converted into a link after the user clicks the submit button. When the user clicks on the link they are redirected to b.html.
<textarea id="sentenceId">
</textarea>
<br>
<button type="button" id="buttonId" onclick="createLink(document.getElementById('sentenceId').value)">Submit
</button>
<p id="demo">
<a id ="link" href="b.html"></a>
</p>
In b.html:
I would like to display the original text.
In script.js:
function createLink(val) {
document.getElementById("link").innerHTML = val;
document.getElementById('buttonId').style.display = 'none';
document.getElementById('sentenceId').style.display = 'none';
}
If you want to open a new page and get the text there, you could use a post-form and an input[type="hidden"] to send the text and display it afterwards.
If you wand the link to be sendable, you'd either have to encode the text as get-parameter or save it to a database and add the id of the entry to the link.
As #Kramb already mentioned, localStorage is a possibility, but only if you stay on the same browser and both pages have the same domain.
Using localStorage
The localStorage property allows you to access a local Storage object. localStorage is similar to sessionStorage. The only difference is that, while data stored in localStorage has no expiration time, data stored in sessionStorage gets cleared when the browsing session ends—that is, when the browser is closed.
a.html
function createLink(val) {
document.getElementById("link").innerHTML = val;
document.getElementById('buttonId').style.display = 'none';
document.getElementById('sentenceId').style.display = 'none';
localStorage.setItem("textArea", val);
}
b.html
function getText(){
var textVal = localStorage.getItem("textArea");
}
Another option would be to use a query string.
a.html
function navigateTo(val){
window.href.location = "b.html?text=" + val;
}
This will pass the value of the text from textarea with the url during navigation. Once b.html has loaded, you can do the following.
b.html
function getText(){
var url = window.location.href;
var queryIndex = url.indexOf("=") + 1;
var passedText = url.substring(queryIndex);
document.getElementById('foo').value = passedText;
}
This is possible using JavaScript. You can do an AJAX call to another page on you website, and search for an element to get its content. In you're case an textarea
I wrote an example on codepen.io for you. Click here
To make things simpler im using jQuery in this example.
So how does it work?
First of, include jQuery inside the <head> tag of you're website.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
I created the following structure
structure
root
scripts
jQuery.min.js
index.js
index.html
textarea.html
Contents of index.html
<!DOCTYPE html>
<html lang="en">
<head>
<!-- Meta -->
<meta charset="UTF-8" />
<title>My New Pen!</title>
<script type="text/javascript" src="scripts/jquery.min.js"></script>
<!-- Styles -->
<link rel="stylesheet" href="styles/index.processed.css">
</head>
<body>
<button id="clickme">To load the textarea content, click me!</button>
<div id="content">The data from the textarea will be shown here, afte you click on the button :)</div>
<!-- Scripts -->
<script src="scripts/index.js"></script>
</body>
</html>
Contents of texarea.html
<textarea id="textarea">
I am the content of the textarea inside the textarea.html file.
</textarea>
Contents of index.js
(function() {
$(document).ready(function() {
/**
* The button which triggers the ajax call
*/
var button = $("#clickme");
/**
* Register the click event
*/
button.click(function() {
$.ajax({
url: "textarea.html",
type: "GET"
}).done(function(response) {
var text = $(response).filter("#textarea").html();
$("#content").append("<br/><br/><strong>" + text + "</strong>");
});
});
});
})()
So what does index.js do exactly?
As you can see i created an Ajax call to the textarea.html file. The .done function holds the response data. The data inside it can be anything depending on the content of the textarea.html file.
$(response).filter("#textarea").html();
The above piece of code filters out the #textarea div and then gets the innerHTML using the jQuery html() function.
If you want to get the value of the textarea through the [value] attribute, you can replace above line to
$(response).filter("#textarea").val();
I believe you want to do this:
function createLink() {
var textvalue = document.getElementById('sentenceId').value;
document.getElementById("link").innerHTML = textvalue;
document.getElementById("buttonId").className ="hideme";
document.getElementById("sentenceId").className ="hideme";
}
.hideme{
display: none;
}
<textarea id="sentenceId">
</textarea>
<br>
<button id="buttonId" onclick="createLink()">Submit
</button>
<p id="demo">
<a id ="link" href="b.html"/>
</p>

Pass variables from Javascript to PHP - Popup/Modal Window

<html>
<head>
<script type="text/javascript">
function showdivv(el, idclicked) {
var iddd = idclicked;
var display = document.getElementById(el).style.display;
if(display == "none")
document.getElementById(el).style.display = 'block';
else
document.getElementById(el).style.display = 'none';
}
</script>
<?php $showw = "<script>document.write(iddd)</script>"; ?>
</head>
<body>
<div id="myDiv" style="display: none;">ID Selected: <?php echo $showw; ?></div>
<?php $variable = 4; ?>
<button type="button" onclick="showdivv('myDiv', '<?php echo $variable; ?>')">Show / Hide</button>
</body>
I'm trying to make a way when a person presses the button pass the variable, in this case ID, to JavaScript and then show the hidden div in PHP. It does not work, can someone help me? THX
If you're okay with the page reloading, you can simply do
window.location.href('php_script_that_needs_your_input.php?id=input_id_from_js');
If not, I absolutely recommend using JQuery as it makes Ajax queries a breeze.
Inside the <head> tags:
<script src='http://code.jquery.com/jquery-2.2.0.min.js'></script>
Upload the script to your own server for production purposes, obviously.
in the <body>, where you want the results from the PHP script to appear (skip this if you don't want output from PHP):
<div id="phpResult"><!--content to be set by ajax--></div>
and put this JS directly below this <div>:
function ajax_on_button_press(resultDiv, id) {
var phpUrl = "php_script.php?id="+id+"&other_variable=cheese&more_info=rats";
$(resultDiv).load(phpUrl);
}
I have used example values here, but you can easily use variables from JavaScript like this:
var other_variable=$('#otherVariableInput').val(); //gets input from a textbox with the html id otherVariableInput
var phpUrl = "php_script.php?id="+id+"&other_variable="+other_variable+"&more_info=rats";
To start the process, you need a button that runs this script. Change your button markup to
<button type="button" onclick="ajax_on_button_press('#phpResult', '<?php echo $variable; ?>')">Show / Hide</button>
If I have understood you correctly, that should solve your problem.

Using JavaScript in "button" self recognition on webpage

I have a website in which I have placed specific buttons inside of articles and outside in the head/body/footer. What I plan to do is when a user clicks on the button the JavaScript code should find out if the button is located inside of an article or outside of it and send the information to my parent website using PHP's $_GET function. This is the code on the 'child' website..
<!-- Button code -->
<p id="test"></p>
<a id ="webs" href= "" onclick="jams(this);document.getElementById('test').frameBorder=0"; target="test"><button>Click me!</button> </a>
The JavaScript functions it calls.
<p id="demo"></p>
<script>
function jams(z) {
var origZ=z;
var found= false;
var sString;
while ( z.nodeName != "HTML" && !found){
var elements = z.getElementsByTagName('a');
for(var i=0; i<elements.length; i++) {
var input = elements[i] ;
sString = input.getAttribute("href");
found = sString.search(window.location.hostname) != -1;
}
z=z.parentElement;
if ( z.nodeName != "HTML" && z.nodeName != "ARTICLE"){
z=z.parentElement;
var spString = (window.location.hostname);
var link = "http://www.parentwebsite.com/one.php?id="+spString;
origZ.href = link;
}
}
var link = "http://www.parentwebsite.com/two.php?id="+sString;
origZ.href = link;
}
</script>
I have two pages on the parent website, page one.php receives the websites name (www.child.com) if the button is located outside of the article. If the button is located within an article page two.php receives the articles URL.Using PHP's $_GET Variable.
$success = $_GET["id"];
So when the user clicks the button on the webpage the button will call the jams script and it recognizes where the button is situated on the webpage and sends to either one.php the website-name OR two.php the articles URL.
The script works just fine when the button is situated within an article,
the href =
http://www.parentwebsite.com/two.php?id=http://child-articles-url.com/
BUT it fails when it is outside of an article, the href
http://www.parentwebsite.com/two.php?id=http://www.parentwebsite.com/one.php?id=http://www.child.com/
What it needs to give is just:
http://www.parentwebsite.com/one.php?id=http://www.child.com/
P.S I have used chrome's debugger while working with this.
Thanks in advance! :)
I tried to solve your problem
index.php
<!DOCTYPE html>
<html>
<head>
<title>Using JavaScript in “button” self recognition on webpage</title>
</head>
<body>
<!-- Your HTML CODE -->
<div class="aricle">
<h2> Article Starts </h2>
This is inside Article
<h2> Article Ends </h2>
</div>
<br />
This is inside Article
<!-- Your JS CODE -->
<script type="text/javascript">
function link(button) {
if (button == 1) {
//alert("button inside article");
window.location.href='http://localhost/stackTest/one.php';
} else if (button == 2) {
//alert("button outside article");
window.location.href='http://localhost/stackTest/two.php';
}
}
</script>
</body>
</html>
one.php
<h2>This is One</h2>
two.php
<h1>This is Two</h2>
Hope this helps you to identify the buttons.
and you can use the anchor (a) tags for displaying as a button instead using <button> tag inside <a>..</a> tag.
If you are using Bootstrap simply use "Button" Class for <a>.

Categories

Resources