Change javascript code to jquery code, How is it? - javascript

I want change following javascript code to jquery code, How is it?
With done change hourOffset in date 3, 21 and 9, 22.
DEMO: http://jsfiddle.net/zJRDC/
<script type="text/javascript">
var interval = self.setInterval("clock()", 1000);
function clock() {
var date = new Date();
var hourOffset = 3;
date.setUTCHours(date.getUTCHours(), date.getUTCMinutes());
var time = date.getTime();
date.setUTCFullYear(date.getUTCFullYear(), 3, 21);
var dstStart = date.getTime();
date.setUTCFullYear(date.getUTCFullYear(), 9, 22);
var dstEnd = date.getTime();
if (time > dstStart && time < dstEnd){ hourOffset = 4;}
date.setUTCHours(date.getUTCHours() + hourOffset, date.getUTCMinutes() + 30);
var output = date.getUTCHours() + ":" + date.getUTCMinutes() + ":" + date.getUTCSeconds();
document.getElementById("clock").innerHTML = output
}
</script>
<div id="clock"></div>​

There's precisely one line of that where jQuery might apply:
document.getElementById("clock").innerHTML = output
which with jQuery could be
$("#clock").html(output);
That uses $ to look up the element, which includes a workaround for a bug in getElementById in earlier versions of IE, and then uses the html method to set the markup on the element (which is very like setting innerHTML — again, though, with some workarounds for problematic bits in some cases; they probably don't apply to this specific code).
Note that jQuery is just a framework written in JavaScript. It smooths over some browser differences dealing with the DOM, and provides a lot of handy utility functionality, but it's not a thing separate from JavaScript. You write JavaScript code, and you optionally use jQuery in it (just like any other library).

if your code works. you don't really need jquery. unless you want to create re-usable function or your custom plugin.
a quick sample to use clock() as jquery plugins (didn't test)
(function( $ ){
$.fn.myClock = function(timeout) {
var interval = setInterval("clock()", timeout);
function clock() {
//..calculate date output
var output = //...
this.html(output)
}
};
})( jQuery );
then to use your plugin
$(document).ready(function(){
$('#clock').myClock(1000);
}
see Plugins/Authoring and learn-how-to-create-your-own-jquery-plugin

JQuery is already done with JavaScript . Nothing to convert because JQuery is not a language ;).

Related

match() or split() messing up my code

I'm new to programming, I'm learning javascript. I don't understand what's wrong with my code but I'm unable to reach the result (i.e. show the total seconds in the text box). The program works fine until matching the pattern. But it's getting all messed up when I'm using the split() function. Please tell me where I'm going wrong. Thank You
<body>
<script>
function cal() {
var text = document.getElementById("pp").innerHTML;
var pattern = text.match(/[0-2][0-9]:[0-5][0-9]:[0-5][0-9]/);
var b = pattern.split(':');
var seconds = (+b[0]) * 3600 + (+b[1]) * 60 + (+b[2]);
document.getElementById("tot").value = seconds;
}
</script>
<div>
<p id="pp">The Time Right Now Is 12:34:56</p>
Total Seconds: <input type=t ext id="tot"><button onclick="cal()"> Click Here!</button>
</div>
</body>
You can check the console (F12 in Chrome) to see if any errors occur. You can also step through the code to see what's going on by adding a debugger; statement there somewhere.
If you move the JavaScript code to a separate file, you can also write tests (for example with Jasmine) to automate testing your code.
All that being said, the following error is displayed in the console:
Uncaught TypeError: pattern.split is not a function
The fix:
var b = pattern[0].split(':');
But once you've started with a Regex, you can continue that way. The following will group the hours, minutes and seconds
var result = "12:34:56".match(/([0-2][0-9]):([0-5][0-9]):([0-5][0-9])/)
var hours = result[1];
var minutes = result[2];
var seconds = result[3];
Better yet, for date parsing like what you are doing here, you could use a library that offers this sort of things out of the box. MomentJS is a very popular one. If this is the only thing you do, using a library is overkill but if you are doing alot of date parsing/formatting, then it will make things much easier for you.
# Install on command line with npm (you can also use bower, ...)
npm install moment
// import and use
import * as moment from "moment";
var parsed = moment("12:34:56", "HH:mm:ss");
String.prototype.split() is a String method, and String.prototype.match() returns an array.
The problem:
You can not applay .split on the returned value from `.match
Solution:
You need to use array index [0] to match the first element from returned array.
Your code after fixing
function cal() {
var text = document.getElementById("pp").innerHTML;
var pattern = text.match(/[0-2][0-9]:[0-5][0-9]:[0-5][0-9]/);
var b = pattern[0].split(':');
var seconds = (+b[0]) * 3600 + (+b[1]) * 60 + (+b[2]);
document.getElementById("tot").value = seconds;
}
<div>
<p id="pp">The Time Right Now Is 12:34:56</p>
Total Seconds: <input type=t ext id="tot">
<button onclick="cal()"> Click Here!</button>
</div>
Pattern return as list. use conditional statement
<body>
<script>
function cal() {
var text = document.getElementById("pp").innerHTML;
var pattern = text.match(/[0-2][0-9]:[0-5][0-9]:[0-5][0-9]/);
b = pattern[0].split(':');
console.log(b)
var seconds = (b[0]) * 3600 + (b[1]) * 60 + (b[2]);
document.getElementById("tot").value = seconds;
}
</script>
<div>
<p id="pp">The Time Right Now Is 12:34:56</p>
Total Seconds: <input type=t ext id="tot"><button onclick="cal()"> Click Here!</button>
</div>
</body>

Script not loading in joomla template

I'm trying to use jquery to display content on my joomla website based on date. Here is the jsfiddle that is working: http://jsfiddle.net/2BHLd/968/
$(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();
});
});
I'm using Jumi to insert the script and css into my page and putting the html into an article. The CSS seems to be working just fine, as it has hidden the html, but for some reason, the script doesn't appear to be showing the text even if the current date is within the date range.
http://askc.org/galacticos/index.php/events/upcoming-events
This joomla template seems to limit what I can do, but I'm thinking I've just made a simple mistake somewhere and I've spent two hours trying to fix it to no avail. Thanks in advance!
You are using $ to reference jQuery, while Joomla reserves that for mootools for legacy reasons.
Simply replace every occurrence of $ with jQuery so the above code will look like:
jQuery(function() {
jQuery(".DateDiv").each(function(index) {
var sRange = jQuery(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)
jQuery(this).show();
});
});
As an alternative, if you really like having the $ prefix, you could reassign it with
$ = jQuery;
just before your script; but this could break other functionality that relies on $ being mootools, and it's not the Joomla preferred way of doing it.
Finally, your code is not very resistant,
var dtTo = new Date(arrTemp[1]);
will break if sRange does not contain at least two items, and the following comparison will produce unpredictable results if the arrTemp items cannot be converted to dates.

javascript timer not working

I have a little javascript which I'm trying to use to make a timer. I got the code from another question on this site and it works ok on it's own, but since I'm making a few timers on this page I need to modify it a little and my modifications break it.
I'm not so brilliant with javascript and I can't see where I'm going wrong. All I've really done is add numerals (the id's of the products which have the timers) to the variable and function names. I've read it's ok to have numerals in variable and function names, so I'm at a loss.
The code I'm using (which isn't working) is:
$(document).ready(function () {
var x1, secs1 = 61434; //declared globally
x1 = setInterval(myFunc1, 1000);
function myFunc1() {
alert('yo');
var minutes = Math.floor(secs1 / 60);
var seconds = secs1 % 60;
$('#timer_'1).html(minutes + ':' + seconds); //assuming there is a label with id 'timer'
secs1--;
if (secs1 == 0) {
document.getElementById('timer').style.hidden = true;
clearInterval(x1);
}
}
});
Your question is unclear, and it's not obvious to me what you're trying to do. But one obvious problem is in these two lines:
$('#timer_'
1).html(minutes + ':' + seconds); //assuming there is a label with id 'timer'
That will throw a syntax error, because '#timer_'1 is not valid syntax.
Two issues here with the css selectors:
$('#timer_'1).html(minutes + ':' + seconds); //add a + between timer_ and 1
document.getElementById('timer') //should be timer_1 too
fiddle http://jsfiddle.net/Drea/1zvLspxd/

How to write arguments in function?

I have been using functions but I am not able to tackle this.
What I have done is created a function, then made this to use the values provided by the document class or ids and do the work. Once work is done then just give the data back! It worked!
Now I want to make this function happen for two divs, the first function works good. The issue is with the second one. The function is correct, their is some other bug while writing the result.
Here is my code:
function time_untilCom(id) {
var Time2 = Date.parse(document.getElementById("time_" + 2).value);
var curTime2 = new Date();
var timeToWrite2 = "";
var seconds2 = Math.floor((curTime2 - Time2) / (1000));
if (seconds2 > 0 && seconds2 < 60) {// seconds..
timeToWrite2 = seconds2 + " seconds ago";
$('#update_' + 2).html(seconds2);
$('#jstime_' + 2).html(timeToWrite2 + " <b>Time that was captured!</b>");
}
}
If I use it as it is, it works! The issue comes when I try to replace these
("time_" + 2), ("#update_" + 2), ("#jstime" + 2) with ("time_" + id), ("#update_" + id), ("#jstime_" + id).
What i want to happen is that the function would be provided with a common ID that is applied throughout the div and use that ID, to get the value of time, convert it to seconds, do other stuff and then provide me with the result in the corresponding element with the id that was in the argument.
function works great, it do provide me with the result. But the issue is with the id its not being sent I guess. Or if is being sent then not being applied. What might be the issue here? And don't mind the seconds i have that covered too.
I am really very sorry for short code:
Pardon me, I was about to write the code for the function too. But electricity ran out!
Here is the code: onload="time_untilCom('2'), this is the way I am executing this.
And once in the main code, it will be executed like this: onload="time_untilCom(#row.Id) because I am using ASP.NET Web Pages I will be using the server side code to write the ID from Database. And will then user the ID throughtout the div to update the time!
From what I understand, you probably want to replace the second line
var Time2 = Date.parse(document.getElementById("time_" + 2).value);
with
var Time2 = Date.parse(document.getElementById(id).value);
And at the end you can also use
$('#'+id).html(timeToWrite2 + " <b>Time that was captured!</b>");
You are passing "id" as an argument, but you never use it inside the function. My question is: In your example you are using 2 as appendix to id attributes. Is it the 2 (or other numbers respectively) that you want to have as the id parameter of the function?
Then you could just replace each + 2 in your code by + id
function time_untilCom(id) {
var Time2 = Date.parse(document.getElementById("time_" + id).value);
var curTime2 = new Date();
var timeToWrite2 = "";
var seconds2 = Math.floor((curTime2 - Time2) / (1000));
if (seconds2 > 0 && seconds2 < 60) {// seconds..
timeToWrite2 = seconds2 + " seconds ago";
$('#update_' + id).html(seconds2);
$('#jstime_' + id).html(timeToWrite2 + " <b>Time that was captured!</b>");
}
}
EDIT: Please tell us where and how exactly do you call time_untilCom? Did you pass the id there?

Show Div When Dates Match Using .Each

I have a list of job postings and would like to display a div that say 'New' when the date is equal to today's date.
To create this I have created a javascript code that will execute on a loop for each set of outer div's, but I am having trouble correctly running the .each function.
Here is the link to a JSFiddle: http://jsfiddle.net/jeremyccrane/2p9f7/
Here is the HTML Code:
<div class="outer">
<div class="job-date">07-Feb-13</div>
<div class="new" style="display:none;">NEW</div>
<div class="value"></div>
</div>
<div class="outer">
<div class="job-date">12-Feb-13</div>
<div class="new" style="display:none;">NEW</div>
<div class="value"></div>
</div>
Here is the Javascript code:
$( ".outer" ).each(function(i) {
var jd = $(".job-date").text();
j = jd.substr(0,2);
var today = new Date();
var dd = ( '0' + (today.getDate()) ).slice( -2 )
$('.value').html(dd + "/" + j);
if(dd === j) {
$('.new').show();
} else {
$('.new').show();
}
return false;
});
Not too sure what you think the problem is but I could see a couple of issues. Mainly, when you do for example:
$('.new').show();
you're calling show() on ALL matching elements of class new, not just the one 'under' the outer you're in. Try this:
$('.new', this).show();
You were setting the new to show whichever way your date comparison went too. I had a stab at updating your fiddle below:
$( ".outer" ).each(function(i) {
var jd = $(".job-date", this).text();
j = jd.substr(0,2);
var today = new Date();
var dd = ( '0' + (today.getDate()) ).slice( -2 )
$('.value', this).html(dd + "/" + j);
if(dd === j) {
$('.new', this).show();
} else {
// $('.new', this).show();
// do something different here
}
});
This code appears to do what you want:
$(".outer").each(function(i) {
var jd = $(this).find(".job-date").text();
var j = jd.substr(0,2);
var today = new Date();
var dd = ('0' + (today.getDate())).slice(-2);
$(this).find('.value').html(dd + "/" + j);
if(dd == j) {
$(this).find('.new').show();
} else {
$(this).find('.new').hide();
}
return false;
});
http://jsfiddle.net/Dk4dQ/
Your main problem was that you were missing all of the $(this).find() calls. You are iterating through containers. Using $(this).find() will get you the controls within those containers. The plain $() calls will find all matching elements in the document, which is not what you want.
The this in this case refers to the container. Wrapping it in the jQuery function lets us use the jQuery find method to get it's children.
Also, as the others mentioned, you were show()ing the div regardless of success or failure, which again is not what you want.
You have 2 problems here. First of all, you're triggering show() regardless of whether the dates match or not:
if(dd === j) {
$('.new').show();
} else {
$('.new').show(); // <-- shouldn't show in this case
}
The second problem is that you're showing everything with the class "new", when you only want to show particular divs. You'll need to give unique IDs to each "new" div, and then fix your code to only show the divs with that particular ID.
You don't need a complicated iterator function. All you need is:
$(".outer .job-date" ).filter(function() {
return (Date.parse($(this).text()) / 86400000 | 0) == (new Date() / 86400000 | 0);
}).next().show();
filter seems like a better choice for what you're doing than each. First we just want the set of elements that have a date equal to today.
To do that we can take the dates and get rid of the time part. Dates are represented in terms of number of milliseconds since the epoch. By dividing by the number of milliseconds in a day (86400000, or 60*60*24*1000) and then truncating any decimal part (javascript idiom: |0) we are comparing the number of full days since the epoch.
Now with a set of elements containing today's date, next() advances every matched element to the next sibling (the hidden div with class new), and show() shows it.

Categories

Resources