Jquery or Javascript that display content based on the date HELP - javascript

Jquery or JavaScript that displays content based on specifics date period
so we have like 3 dates
12/3/2010
12/11/2010
12/20/2010
and
Div Contents
Content 1 should be displaying from 12/3 to 12/11
Content 2 should be display from 12/11 to 12/20
and Content 3 should be displaying from 12/20 there after

First, like others said this whole thing is bad idea as you're depending on the client machine date/time and correct approach would be doing that in server side.
Anyway, guess you have your reasons so here is jQuery solution.
Have such HTML:
<div class="DateDiv"><span class="DateRange">1/1/2010 to 1/1/2011</span>I'll be visible during 2010</div>
<div class="DateDiv"><span class="DateRange">1/1/2011 to 1/1/2012</span>I'll be visible during 2011</div>
<div class="DateDiv"><span class="DateRange">1/1/2012 to 1/1/2013</span>I'll be visible during 2012</div>
Put the date range inside a span inside each div with the class "DateRange".
Next, have such CSS to have them initially hidden:
<style type="text/css">
.DateRange, .DateDiv { display: none; }
</style>
And finally, this script: (jQuery)
<script type="text/JavaScript">
$(function() {
$(".DateDiv").each(function(index) {
var sRange = $(this).find(".DateRange").html();
var arrTemp = sRange.split(" to ");
var dtFrom = new Date(arrTemp[0]);
var dtTo = new Date(arrTemp[1]);
var dtNow = new Date();
if (dtNow >= dtFrom && dtNow <= dtTo)
$(this).show();
});
});
</script>
Test case is available here feel free to mess around with it: http://jsfiddle.net/2BHLd/

I've created a simple code. It should work as you want (if I have understood you well).
I know, there's no doctype in my HTML and there are some missing tags. The HTML I've provided is just a kind of template.
<html>
<head>
<script type="text/javascript">
var date=new Date();
var year=date.getFullYear();
var month=date.getMonth();
var day=date.getDate(); // fixed
function SetDivContent() {
var div=document.getElementById('date_dependent');
if (year==2010 && month==11) { // fixed (the JavaScript months order is 0-11, not 1-12)
if (day>=3 && day<11) { // the following content will be displayed 12/03/2010, 12/04/2010, [...], 12/09/2010, 12/10/2010
div.innerHTML='content 1';
}
else if (day==11 || day==12) { // this one will be displayed 12/11/2010 and 12/12/2010
div.innerHTML='content 2';
}
else if (day>12) { // this one - 12/13/2010 and later, until the end of December
div.innerHTML='content 3';
}
}
else if (year==2011 && month>=0) div.innerHTML='content 3'; // OPTIONAL - just to ensure that content 3 is displayed even after December.
}
</script>
</head>
<body onload="SetDivContent()">
<div id="date_dependent"></div>
</body>
</html>
Please note that if you want to hide some data from users if the specified date hasn't come yet, you should better use something server-side for security reasons. Otherwise, any user may just read the page's source. Also remember that the following code is executed when the body is loaded, i.e. each time a user refreshes the page.
EDIT: Warning: there were two bad lines (I've made a mistake before). Anyway, I've fixed them. The current code works, I've tested it.

Related

Why does my Javascript Function stop working after a certain period of time?

First things first, I'm brand new to Javascript and Regex. I've only been dipping my toes in this past month. I've been trying to put together away to paste a url into a text input then automatically trim it down to just the host name and validate it before I'm able to push the button.
I've gotten it working a few different times but I keep running into the same issue: After a certain period of time, it simply stops working.
I've reformatted and cleaned up the code a few times (though, I'm sure it's still very sloppy because I'm new at this) and I can get it working again. But after an hour or so of working, it stops working. Reloading the page doesn't make a difference. Even restarting my computer doesn't make a difference. It simply stops working.
My only guess is that there must be something about the way I'm going about this which is causing it crash or stall out. Perhaps a formatting issue, perhaps the methodology altogether is flawed. I just don't know enough to be able to diagnose it yet.
Hopefully, some of you nice people would be able to point out my flaws or point me in the right direction of how to fix this. I've searched and I couldn't find anyone who was trying to do the things I'm doing all in one build (preparing to myself to be proved wrong here).
Here's the code:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Untitled Document</title>
</head>
<body>
<input id="notesUrlInput" type="text" placeholder="URL Goes here" pattern="^(?!www\.)[a-zA-Z0-9\-]+\.[a-zA-Z0-9]+$" autocomplete="off">
<button id="notesExecuteButton" disabled>Execute</button>
<span id="notesUrlOutput"></span>
<!------------------------------------------------------------------------------->
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.5/js/bootstrap.min.js"></script>
<script>
(function () {
var timeout = null;
var notesUrlOutput = document.getElementById("notesUrlOutput");
var notesExecuteButton = document.getElementById("notesExecuteButton");
document.getElementById('notesUrlInput').addEventListener('keyup',
function (e) {
clearTimeout(timeout);
timeout = setTimeout(
function () {
rawInput = $('#notesUrlInput').val();
cleanInput = rawInput.replace('www.', '');
cleanInput = cleanInput.replace('http://', '');
cleanInput = cleanInput.replace('https://', '');
cleanInput = cleanInput.replace(/\/.*/,'');
$('#notesUrlInput').val(cleanInput);
if (cleanInput.value == "") {
notesUrlOutput.innerHTML = "";
notesExecuteButton.disabled = true; return false;
} else if(!notesUrlInput.checkValidity()) {
notesUrlOutput.innerHTML = "Invalid URL: Please provide a valid URL";
notesExecuteButton.disabled = true; return false;
} else {
notesUrlOutput.innerHTML = "Input OK";
notesExecuteButton.disabled = false; return false;
}
}, 400);
});
})();
</script>
</body>
</html>
Frustratingly, when I pasted this code in here and ran it, it worked. As soon as I opened the file I copied this from in my browser. It stopped working. I just don't understand it.
From your code it looks like you want to extract just the domain name from the input field.
You mix JavaScript DOM calls and jQuery, which is fine. It is usually easier to interact with the DOM using just jQuery. Here is your code rewritten in jQuery:
const cleanRegex = /^https?:\/\/(?:www\.)?(.*)\/.*$/;
const validRegex = /^[\w\-]+(\.[\w]+)+$/;
(function () {
$('#notesExecuteButton').prop('disabled', true);
$('#notesUrlInput').on('input', function(event) {
let val = $(this).val();
let cleaned = val.replace(cleanRegex, '$1');
$(this).val(cleaned);
if(!cleaned) {
$('#notesUrlOutput').text('');
$('#notesExecuteButton').prop('disabled', true);
} else if(!cleaned.match(validRegex)) {
$('#notesUrlOutput').text('Invalid URL: Please provide a valid URL');
$('#notesExecuteButton').prop('disabled', true);
} else {
$('#notesUrlOutput').text('Input OK');
$('#notesExecuteButton').prop('disabled', false);
}
});
})();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>
<input id="notesUrlInput" />
<button id="notesExecuteButton" style="disabled: disabled;">Go</button>
<div id="notesUrlOutput"></div>
Explanation:
.on('input') - fires every time something changes in the input field- val.replace(cleanRegex, '$1') - clean up: strip protocol and www prefix, and URL path (any text after domain
cleaned.match(validRegex) - check validity of domain
.prop('disabled', true/false) - add/remove disable property

How to print out content of iframe

I have some response from a server and I have put the response in the content of iframe. Essentially what I need is the item number (see screenshot below), in this case it's 13.
So I tried doing console.log($("#iframe").contents()); which prints out:
I have tried looking through this but cannot find the item number. Is there a easier way to get to the body and obtain the number?
As I understand the question:
There is an <iframe>
The <iframe> has content in a string (i.e. item = 13) that's in a <pre>
But you just want the number from said string (i.e. 13);
The following Demo 1 accomplishes the objectives listed above using plain JavaScript and Demo 2 uses jQuery.
Note: jQuery can be significantly slower than JavaScript which is apparent when dealing with loading iframes. Keep in mind that iframes are the slowest part of your load time. If it doesn't look like you are getting the iframe at all, then run your iframe dependant functions at window.onload.
Also of note: both versions of the function getNumberFromFrame(iframe, target) are reusable. You can use this function on a single element within an iframe and if the target element has any text with numbers✎, it will extract those numbers regardless of the how the string is patterned.
ex. "item = 13" // 13
ex. "August 23, 2017" //23 2017
✎ Edited the regular expression on line 33 to replace non-number matches to a space.
Details are commented in Demo 1 and Demo 2
Demo 1: PLUNKER - Plain JavaScript
Demo 2: PLUNKER - jQuery
Demo 1 - Plain JavaScript: STACK
This is provided as site requires us to post code on the answer, be aware that this copy does not function due to SO security measures. Please review the functioning PLUNKER instead
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
<script src="script.js"></script>
</head>
<body>
<h1>Parent Page</h1>
<iframe id='ifrm1' name='ifrm1' src='child_page.html' width='200' height='200' scrolling='no' frameborder="1"></iframe>
<br> Result:
<output id='display'></output>
<script>
/* Pass an iframe and it's targeted content as
|| selectors (e.g. "TAG", "#ID", ".CLASS", etc)
*/
function getNumberFromFrame(iframe, target) {
// Reference the iframe
var iFrm = document.querySelector(iframe);
/* Reference the iframe's Document Object by
|| using .contentDocument OR
|| .contentWindow.document properties
*/
var iDoc = iFrm.contentDocument || iFrm.contentWindow.document;
/* Now reference the target parameter with
|| the iframe's Document Object.
*/
var iSel = iDoc.querySelector(target);
// Get the target's text
var iTxt = iSel.textContent;
// Then filter out everything but numbers
var iNum = iTxt.replace(/^\D+/g, '');
// Ensure it is a number
iNum = parseFloat(iNum);
// Return number.
return iNum;
}
/* When Window Object is loaded:
|| Call getNumberFromFrame()
*/
window.onload = function() {
var result = getNumberFromFrame('#ifrm1', 'pre');
var view = document.getElementById('display');
view.textContent = result;
};
</script>
</body>
</html>
Demo 2 - jQuery: STACK
This is provided as site requires us to post code on the answer, be aware that this copy does not function due to SO security measures. Please review the functioning PLUNKER instead
<!doctype html>
<html>
<head>
</head>
<body>
<h1>Parent Page</h1>
<iframe id='ifrm1' name='ifrm1' src='child_page.html' width='200' height='200' scrolling='no' frameborder="1"></iframe>
<br> Result:
<output id='display'></output>
<script src='https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js'></script>
<script>
/* Pass an iframe and it's targeted content as
|| selectors (e.g. "TAG", "#ID", ".CLASS", etc)
*/
function getNumberFromFrame(iframe, target) {
/* .contents() method "opens" iframe
|| .find() will find the specified target
|| inside of iframe.
*/
var iEle = $(iframe).contents().find(target);
// Get text of target
var iTxt = iEle.text();
//console.log(iTxt);
/* Replace anything that's not a number with
|| nothing.
*/
var iNum = iTxt.replace(/^\D+/g, '');
// Ensure it is a number
//console.log(iNum)
var iRes = parseFloat(iNum);
// Return number.
return iNum;
}
// When Window Object is loaded...
/* Find the element with the id of #display
|| Set output#display text to the return of
|| getNumberFromFrame('#ifrm', 'pre')
*/
window.onload = function() {
$('#display').text(getNumberFromFrame('#ifrm1', 'pre'));
}
</script>
</body>
</html>
Here is a JQuery approach and it's very simple
// this will get you item = 13
var result = $("#iframe").contents().find("pre").html();
// this will get you 13
result = result.split("=")[1];
// 13
alert(result);
You can try this.
console.log($("#iframe")["0"].contentDocument.body.firstElementChild.innerText);
Working evidence

Do I need to load JQuery to make this work?

I have two drop down boxes that represent year intervals. The user will select a year from the first one (say 2002), and the next drop down box will automatically be filled with years that equal or are greater than the first (2002 and above). I believe I have the correct javascript code (year.js).
Here it is:
$("#first").change(function(){
var val = $("#first option:selected").html();
$("#second").html("");
var d = new Date();
var n = d.getFullYear();
for (i=val; i<=n;i++){
$("#second").append("<option>" + i + "</option>");
}
});
Here is part of my html form code:
<body>
<script src="year.js"></script>
<select id= "first">
// Here, I gather my years from my database
</select>
<select id= "second">
</select>
When I run this, Nothing happens with my second drop down menu. Do I need to load something else into my code like JQuery? If so, how do I do that? Sorry, I am not very familiar with JQuery. Any help would be greatly appreciated.
Yeah you need to load jQuery library to use jQuery function.
you must load the jQuery library before using it's function.
example
<script src="jquery.js"></script> //a local version
or
<script src="http://code.jquery.com/jquery-latest.min.js.js"></script>
<script src="year.js"></script>
Download jQuery library from http://jquery.com/download/
Updated after OP's comment about http://jsfiddle.net/YNuna/1/
you have laoded jQuery library in fiddle.I have marked it with red color in the image below.
also wrap you code in $(document).ready(function ()
$(document).ready(function () {
$("#first").change(function () {
var val = $("#first option:selected").html();
$("#second").html("");
var d = new Date();
var n = d.getFullYear();
for (i = val; i <= n; i++) {
$("#second").append("<option>" + i + "</option>");
}
});
});
If you're copy-pasting javascript code from anywhere and you see a $ sign, a good rule of thumb is that it uses jQuery.
See here for adding it to your page: http://learn.jquery.com/about-jquery/how-jquery-works/

Display html content between defined hours mon to friday

i was wondering if there is a quite simple solution to display content between certain hours and only during working days in a Europe timezone?
The hours will be everyday (except weekends) between 9AM and 5PM, between those times a html content should be shown.
If possible a different html content from 5PM till 9AM.
The short version is that you use new Date() to get the current date/time, and then you use DOM manipulation to add/remove that content as appropriate. If you want content to change in-between page loads, you'll probably also want a window.setInterval running to update things constantly.
You might want to check out the Moment.js library (http://momentjs.com/), as it has a number of functions which make working with dates/times easier.
Here's a quickie example (without using Moment) that just checks "are we past 5 or not?":
window.setInterval(function() {
if (new Date().getHours() > 17) { // if it's after 5pm (17:00 military time)
$('#someContent').hide();
} else {
$('#someContent').show();
}
}, 1000 * 60) // this will run every minute
With that hopefully you can figure out how to add the other needed if checks.
Here you go! :)
<html>
<head>
<script type="text/javascript">
var date=new Date();
var year=date.getFullYear();
var month=date.getMonth();
var day=date.getDate(); // fixed
function SetDivContent() {
var div=document.getElementById('date_dependent');
if (year==2010 && month==11) { // fixed (the JavaScript months order is 0-11, not 1-12)
if (day>=3 && day<11) { // the following content will be displayed 12/03/2010, 12/04/2010, [...], 12/09/2010, 12/10/2010
div.innerHTML='content 1';
}
else if (day==11 || day==12) { // this one will be displayed 12/11/2010 and 12/12/2010
div.innerHTML='content 2';
}
else if (day>12) { // this one - 12/13/2010 and later, until the end of December
div.innerHTML='content 3';
}
}
else if (year==2011 && month>=0) div.innerHTML='content 3'; // OPTIONAL - just to ensure that content 3 is displayed even after December.
}
</script>
</head>
<body onload="SetDivContent()">
<div id="date_dependent"></div>
</body>
</html>
answered Nov 30 '10 at 22:16
rhino

Manipulate DOM element to extract some nodes and remove others

I need to manipulate HTML code. Specifically, the user should be able to copy/paste the code to create an AddThis button in a textarea, and I want to manipulate the pasted code.
A typical AddThis button looks like this :
<!-- AddThis Button BEGIN -->
<div class="addthis_toolbox addthis_default_style ">
<a class="addthis_button_facebook_like" fb:like:layout="button_count"></a>
<a class="addthis_button_tweet"></a>
<a class="addthis_counter addthis_pill_style"></a>
</div>
<script type="text/javascript">var addthis_config = {"data_track_clickback":true};</script>
<script type="text/javascript" src="http://s7.addthis.com/js/250/addthis_widget.js#pubid=ra-123456798"></script>
<!-- AddThis Button END -->
It consists of start and end comments, a div and/or some links, followed by 2 scripts: a config setting, and a call to their library.
The problem is, we need to call this many times on the page ; so, if I just put this every time I want to place an AddThis button, I fear that at least some browsers will have weird behavior, if it works at all.
So, I want to extract the config setting and the lib call, so I can call them just once, and extract the buttons config, so I can place it as many times as I want on the page.
I have already done that :
var codeAT = $(this).val();
if (codeAT.indexOf("AddThis Button BEGIN") >= 0) {
codeAT = codeAT.replace("<", "<");
codeAT = codeAT.replace(">", ">");
codeAT = $(codeAT);
// extract the call to the config var and the lib
var scriptConfig = "";
var scriptSRC = "";
codeAT.each(function() {
if ($(this).attr("nodeName") == "SCRIPT") {
if ($(this).attr("src") && $(this).attr("src") != "") {
scriptSRC = $(this).attr("src");
} else {
scriptConfig = $(this).text();
}
}
});
// extract the addthis identifier
scriptSRC = scriptSRC.split("=")[1];
}
Now, I can use the vars scriptConfig (with var addthis_config = {"data_track_clickback":true};) and scriptSRC (with ra-123456789), and they have the correct values.
What I want now, is the original code (between the two comments), without the comments, and without the script tags.
To remove the tags, I tried to use codeAT.remove($(this)), but it crashes (something about c.replace not being a function).
To get the code back, I tried codeAT.html(), but it gets only the tags.
Instead of .each() I'd do:
//remove <script> tags and get required info
var scriptSRC = $('script[src]', codeAT).remove().attr('src');
var scriptConfig = $('script:not([src])', codeAT).remove().text();
//get the code (as string)
var code = $('<div>').append(codeAT).remove().html();

Categories