Converting hard coded JQuery to a plugin - syntax issues - javascript

I have some JQuery that loads one of many elements, for example one <li> in an unordered list out of many rows of list items as such:
this.randomtip = function(){
var length = $("#tips li").length;
var ran = Math.floor(Math.random()*length) + 1;
$("#tips li:nth-child(" + ran + ")").show();
};
$(document).ready(function(){
randomtip();
});
However, I thought it would be nice to convert this to a JQuery plugin to make it more global in use so I could simply call it when I need it for different elements and use cases.
I realized I needed to take the specific selectors out and convert them to $(this) probably based on looking at some code of other JQuery plugins.
This is what I have so far but am getting alot of syntax errors. I have tried many different iterations of the same thing for several hours but no joy:
(function ( $ ) {
$.fn.randomtip = function () {
var length = $(this).length;
var ran = Math.floor(Math.random()*length) + 1;
$(this).find (':nth-child' '+ ran + ')").show();
})(jQuery);
Where I am getting the syntax error is where I have:
$(this).find (':nth-child' '+ ran + ')").show();

You have a few typos on the $(this).find() line. Below is the correct version:
(function ( $ ) {
$.fn.randomtip = function () {
var length = $(this).length;
var ran = Math.floor(Math.random() * length) + 1;
$(this).find (':nth-child('+ ran + ')').show();
})(jQuery);

There is a syntax problem in
$(this).find (':nth-child' '+ ran + ')").show();
Maybe you want this?
$(this).find (':nth-child(' + ran + ')').show();

Related

How to create an “unlimited” number of independent timers as individual list items in an unordered list with Javascript or jQuery?

I am trying to write a function which when executed (e.g. user clicks a button or image) creates and displays a new timer as a new list item in an unordered list (jQuery Sortable list). It doesn’t need to be super accurate so SetInterval should work fine. It doesn’t need any stops or resets. I would like the user to be able to create as many new independent (count-up) timers (as list items) in the list as they want, theoretically (although in reality there will likely be less than 10-15 on the go at the same time).
The following code does achieve this (or at least does the first time it is run). Subsequent clicks cause grief as I suspect that the same id is being used more than once for both “minutes” and “seconds” causing a conflict between list items.
function listTimer() {
var sec = 0;
function pad ( val ) { return val > 9 ? val : "0" + val; }
setInterval (function(){
document.getElementById("seconds").innerHTML=pad(++sec%60);
document.getElementById("minutes").innerHTML=pad(parseInt(sec/60,10));
}, 1000);
$(document).ready(function(){
$("#sortable1").append('<li class="ui-state-default">' + '<span id="minutes">' + '' + '</span>' + ':' + '<span id="seconds">' + '' + '</span>' + '</li>');
});
}
To allow multiple timers I then figured that each time the function is executed, the values should increment so they are seen as separate. As such I tried
Var i = 0;
function listTimer() {
var sec = 0;
function pad ( val ) { return val > 9 ? val : "0" + val; }
setInterval (function(){
document.getElementById("seconds"+i).innerHTML=pad(++sec%60);
document.getElementById("minutes"+i).innerHTML=pad(parseInt(sec/60,10));
}, 1000);
$(document).ready(function(){
$("#sortable1").append('<li class="ui-state-default">' + '<span id="minutes"+i>' + '' + '</span>' + ':' + '<span id="seconds"+i>' + '' + '</span>' + '</li>');
i=++;
});
}
The “seconds” + i ( and “minutes” =i ) in the .innerHTML works because if I leave var i=0 and then hard code “seconds0” and “minutes0” (instead of “seconds”+i etc) in the span id, a timer is generated as planned (once). The trick is that the “seconds” + i (and “minutes” =i ) in the span id do not work as I imagined. If I leave it as per the code above (e.g. in both the .innerHTML and span id) no list item is generated. I suspect the problem is in incrementing the span id.
Addressing the “span id=” to increment it (multiple ways) does not seem to have helped.
I have tried declaring and inserting a variable with no luck:
var newSeconds= “seconds” +i;
var newMinutes= “seconds” +i;
$(document).ready(function(){
$("#sortable1").append('<li class="ui-state-default">' + '<span id=newMinutes >' + '' + '</span>' + ':' + '<span id=newSeconds>' + '' + '</span>' + '</li>');
I have tried changing the id of the span just prior to the append with either:
document.getElementById("seconds").setAttribute("id", "seconds" +i);
document.getElementById("minutes").setAttribute("id", "minutes" + i);
or
document.getElementById("seconds").id("seconds" +i);
document.getElementById("minutes").id ("minutes" + i);
or
var newSeconds= “seconds” +i;
var newMinutes= “seconds” +i;
document.getElementById("seconds").setAttribute("id", newSeconds);
document.getElementById("minutes").setAttribute("id", newMinutes);
or by combinations of these e.g putting quotation marks around the newSeconds/newMinutes in both the .id and .setAttribute.
but I can’t seem to make the append method work and create a new independent list timer each time the trigger is clicked. The timers jump all over the place (or not at all) when the function is executed multiple times.
I have tried searching for javascript or jQuery ways of doing this but I can only seem to see previous questions that revolve around a certain number of timers (and hard coding them e.g. timer1, timer2 etc) rather than an "unlimited" number of timers. I have looked at books on Javascript and jQuery but can't seem to nut out the solution.
I am hoping I have given a minimal reproducible example. I am obviously missing fundamental issues but am unconscious incompetent at the moment. Is anyone happy to show me the error of my ways and help me get the function working?
I think that the issue stems from your referring to the timers by their Id attributes - an Id attribute is supposed to appear once per page, so having it appear in each timer will definitely cause some confusion.
I would recommend a different structure as well for organization. Here are my thoughts in pseudocode (leaving the implementation up to you)
const $timerContainerDiv = $("…"); // the place where timers live
var timers = []; // this is an array containing all of your timers
// function to add a new timer to the array
var addTimer = function(int minutes, int seconds, int title) {
// html that defines the actual structure of the timer,
// including elements for hours and minutes, each identifiable
// by a js class, and each one including a data attribute giving its value
// for example:
var $timer = $("<div class='timer' data-minutes='" + minutes + "' data-seconds='" + seconds + "' title='" + title + "'>");
timers.push(timer);
}
// now define a timer function to update all timers once per second
var updateTimers = function() {
// update each timer, decrementing one second
$.each(timers, function(index, val) {
var $timer = $(val);
var minutes = $timer.data("minutes");
var seconds = $timer.data("seconds");
var title = $timer.attr("title");
seconds--;
// need logic for when seconds goes negative to reset to 59 and decrement minutes
// need logic for when timer done, etc
$timer.empty();
$timer.append("<span>" + title + ": " + minutes + ":" + seconds + " remaining</span>");
});
setTimeout(updateTimers,1000); // call itself
}
updateTimers(); // get the whole thing started

Syntax error code - Java script

Normally My code is working fine. but, I get Syntax error. what is mistake in syntax here?
$(document).ready(function() {
$('.myClass').change(function() {
var ids = ['first', 'second'];
var totalCount = ids.reduce((prev, id) => parseInt($(`#${id}-passenger`).val()) + prev, 0);
var mc = $('input[name="myClass"]:checked + label').text();
$('#myTotal').val(totalCount + ' - '+mc);
});
});
Maybe you have a Javascript version issue and you should try without templating ?
var totalCount = ids.reduce(function (prev, id) {
return parseInt($('#' + id + '-passenger').val()) + prev
}, 0);
Hope it helps.
Your code is entirely valid and works fine. Therefore I would surmise that this issue is simply that the JS linter in the IDE you're using is outdated and doesn't support ES6. I'd suggest using a more up to date linter, assuming the IDE lets you change it, or even a better IDE entirely.
If you want to avoid the issue you would need to remove the template literals and arrow functions, like this:
$('.myClass').change(function() {
var ids = ['first', 'second'];
var totalCount = ids.reduce(function(prev, id) {
return parseInt($('#' + id + '-passenger').val()) + prev, 10);
}, 0);
var mc = $('input[name="myClass"]:checked + label').text();
$('#myTotal').val(totalCount + ' - ' + mc);
});

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?

Javascript eval

I am trying to get the following working. It seemed to work initially, but somehow it stopped working
var setCommonAttr = "1_row1_common";
var val = document.getElementById("abc_" + eval("setCommonAttr")).value;
what is wrong with above?
The above code is little different from what I am trying to accomplish. I gave the above example just not to make things complicated here. Below is what I am trying to accomplish:
First I am getting an existing element as follows. The element is a
<tr id="row_1_4_2009_abc" class="rowclick">
<td></td>
</tr>
I am using jquery to get the id on click of a row:
$(".rowclick").click(function() {
var row_id = $(this).attr("id");
var getAttributes = row_id.split("_");
var setCommonAttr = getAttributes[1] + "_" + getAttributes[2] + "_" + getAttributes[3] + "_" + getAttributes[4];
var new_row_id = document.getElementById("new_row_" + setCommonAttr).value;
});
You shouldn't need eval() to do this. The value you want is already a variable in JavaScript. Try:
var setCommonAttr = "1_row1_common";
var val = document.getElementById("abc_" + setCommonAttr).value;
Will everything be in that form? row_xxx_xxx_xxx_xxx
if so, why not var new_row_id = document.getElementById("new_" + row_id).value;
You don't need to call eval().
You can just concatenate the string with the variable:
var setCommonAttr = "1_row1_common"; var val = document.getElementById("abc_" + setCommonAttr).value;

Categories

Resources