Why isn't this working - JS [closed] - javascript

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I am working on a project to check to see if a new items is updated on a website. I want to the program to check every second to see if a new item has come in. The items are designated by an ID (which I can get). However, I am having trouble using AJAX to update the part of the website. I want it to 'refresh' the website every second and compare the most recent item to its previous most recent item (i.e. if current > past). Any help would be much appreciated.
<!DOCTYPE html>
<html>
<head>
<script src="jquery-2.1.1.js"></script>
</head>
<body>
<button onclick = "body()">Click Me</button>
<script>
var highest = 0;
var compare = 0;
var creator;
var newItem = false;
var HelpPeople = 'People's Names';
var elements = document.getElementsByClassName('ms-itmhover');
highest = elements[0].getElementsByClassName('ms-vb2')[1].innerText;
var body = function()
{
window.setTimeout(update(), 1000);
}
var update = function()
{
window.jquery-2('body').load('URL');
elements = document.getElementsByClassName('ms-itmhover');
compare = elements[0].getElementsByClassName('ms-vb2')[1].innerText;
creator = elements[0].getElementsByClassName('ms-vb-user')[0].innerText;
if(compare > highest && creaCompare(creator))
{
displayNew();
}
body();
}
var creaCompare = function(create)
{
var comparer = false;
for(var i = 0; i < HelpPeople.length; i++)
{
if(create == HelpPeople[i])
{
comparer = true;
}
}
return comparer;
}
var displayNew = function()
{
confirm('There is a new item');
body();
}
</script>
</body>
I think I asked the question wrong. I am looking to run this on a website (not my own) and have it parse out data and check for new items (AJAX). I am wondering how to use it and how I can use JS on this website (can I run it through the console?)

I rewrote your code because you're using jQuery... but not using it.
<!DOCTYPE html>
<html>
<head>
<script src="jquery-2.1.1.js"></script>
</head>
<body>
<button id="btnTest">Click Me</button>
<script type="text/javascript">
// wait for document loaded
$(function () {
var updateUrl = 'put your update url here';
var highest = 0;
var compare = 0;
var creator;
var newItem = false;
var HelpPeople = 'People's Names';
var elements = $('.ms-itmhover'); // where's this element
highest = $('.ms-vb2', elements).text(); // where are those elements ????
var body = function () {
$('#btnTest").prop('disabled', true);
setTimeout(update, 1000);
};
var update = function()
{
$('body').load(updateUrl, function (response, status, xhr) {
if ( status == "error" ) {
alert("Sorry but there was an error : " + xhr.status + " " + xhr.statusText);
return;
}
elements = $('.ms-itmhover');
compare = $('.ms-vb2', elements).text();
creator = $('.ms-vb-user', elements).text();
if (compare > highest && creaCompare(creator))
{
displayNew();
}
body();
});
};
var creaCompare = function(create) {
var comparer = false;
for (var i = 0; i < HelpPeople.length; i++)
{
if(create == HelpPeople[i]) {
comparer = true;
}
}
return comparer;
};
var displayNew = function() {
confirm('There is a new item');
body();
};
// prevent button click more than once
$('#btnTest").one('click', body);
});
</script>
</body>
As for answering the actual question, without more HTML, there's not much that can be answered. But the above change presumably fixes :
Executing JS code before document is loaded; now wait until page has loaded
Properly make use of jQuery's DOM traversal and manipulation functions.
Better HTML/JS separation
Encapsulate variables in "private" scope (prevent global namespace pollution) (thank you George Mauer)
You had invalid variable names (i.e. jquery-2 is not what you expect, and 2(..) is an invalid syntax)
Your had setTimeout(update(), 1000); which does nothing since it's essentially doing setTimeout(undefined, 1000);
You processed your updated HTML perhaps before it was even loaded (Ajax is async!)
What this answer does not cover :
What is the actual error (the question does not really specify)
Give a concrete working solution, since parts of the HTML is missing

The problem is probably on this line:
window.jquery-2('body').load('URL');
It's not even a valid syntax. It should be written like this:
$('body').load('URL'); // Instead of 'URL' there also should be a proper URL
Also you should know the load function is asynchronous so if you need to do something with loaded elements, you need to put these actions in a callback. (A function passed as a second arguments of the load method.)

Related

JavaScript Countdown with argument passing in

You are given an integer called start_num. Write a code that will countdown from start_num to 1, and when the countdown is finished, will print out "Liftoff!".
I am unsure how to do this and keep getting stuck.
This is the code I am provided with at the beginning of the problem:
function liftoff_countdown(start_num) {
// My code goes here!
}
And then they want me to pass in a value such as the 5:
liftoff_countdown(5);
And then this will be my output:
6
5
4
3
2
1
"Liftoff!"
Thanks!
Look at this maybe help you to create your own code
make two file in a same folder (script.js and index.html)
index.html
<!doctype html>
<head>
<title>Countdown</title>
</head>
<body>
<div id="container">
<div id="inputArea">
</div>
<h1 id="time">0</h1>
</div>
<script src="script.js"></script>
</body>
</html>
script.js
var valueRemaining;
var intervalHandle;
function resetPage() {
document.getElementById("inputArea").style.display = "block";
}
function tick() {
var valueDisplay = document.getElementById("time");
valueDisplay.innerHTML = valueRemaining;
if (valueRemaining === 0) {
valueDisplay.innerHTML = "Liftoff!";
clearInterval(intervalHandle);
resetPage();
}
valueRemaining--;
}
function startCountdown() {
var count = document.getElementById("count").value;
if (isNaN(count)) {
alert("Please enter a number!");
return;
}
valueRemaining = count;
intervalHandle = setInterval(tick, 1000);
document.getElementById("inputArea").style.display = "none";
}
// as soon as the page is loaded...
window.onload = function () {
var inputValue = document.createElement("input");
inputValue.setAttribute("id", "count");
inputValue.setAttribute("type", "text");
// create a button
var startButton = document.createElement("input");
startButton.setAttribute("type", "button");
startButton.setAttribute("value", "Start Countdown");
startButton.onclick = function () {
startCountdown();
};
// add to the DOM, to the div called "inputArea"
document.getElementById("inputArea").appendChild(inputValue);
document.getElementById("inputArea").appendChild(startButton);
};
in this example you have many things to understand how javascript works behind scenes.
How about this...
function liftoff_countdown()
{
var span=document.getElementById('num');
var i=document.getElementById('num').innerText;
i=i-1;
span.innerText=i;
if (i==0){
span.innerText='Liftoff!';
clearInterval(count_down)
}
}
var count_down=setInterval(liftoff_countdown,1000);
<span id="num">5</span>
You can achieve this with a simple recursive function and the use of setTimeout to recursively call the function after a time lapse of 1 second.
function lift_off(seconds) {
if(seconds == 0) {
console.log('liftoff');
} else {
console.log(seconds--);
setTimeout(function(){lift_off(seconds);},1000);
}
}
lift_off(10);
Here is a working JSFiddle
Preface
A lot of these answers seem to be focused on doing things with timers and recursion. I do not believe that is your intent. If your only goal is to print those values to the console, you could simply do the following (see the comments for an explanation).
The Answer
function liftoff_countdown(start_num) {
// Loops through all values between 0 and start_num
for(int i = 0; i < start_num; i++) {
// Prints the appropriate value by subtracting from start_num
console.log( start_num - i );
}
// Upon exiting the loop, prints "Liftoff!"
console.log("Liftoff!");
}
Additional Thoughts
You could just as easily loop backwards through the numbers instead of forward like so:
for(int i = start_num; i > 0; i--){
console.log( i );
}
I tend to lean towards iterating forwards just because it's more common, and it's often easy to confuse readers of your code if they gloss over the loop initialization.
Additionally, I am working with the assumption that when you say "print" you mean "console.log()". If this is untrue, you could of course use any other function in its place (e.g. alert( "Liftoff!" );).

Making dynamically added p elements clickable

I am trying to make the elements clickable. However on clicking any of the <p> elements there is no alert box saying "hello". Please could you look at my code and possibly point me in the right direction?
function createLink(text, parentElement) {
var a = document.createElement('p');
var linkText = document.createTextNode(text);
a.appendChild(linkText);
a.onclick = function(e) {
e.preventDefault();
alert("hello");
};
parentElement.appendChild(a);
var br = document.createElement('br');
parentElement.appendChild(br);
}
var txtFile8 = new XMLHttpRequest();
txtFile8.open("GET", "http://www.drakedesign.co.uk/mdmarketing/uploads/date.txt", true);
txtFile8.onreadystatechange = function() {
if (txtFile8.readyState === 4) { // Makes sure the document is ready to parse.
if ((txtFile8.status == 200) || (txtFile8.status == 0)) { // Makes sure it's found the file.
allText8 = txtFile8.responseText;
arrayOfLines8 = allText8.match(/[^\r\n]+/g);
for (i = 0; i < arrayOfLines8.length - 1; i++) {
createLink(arrayOfLines8[i], document.getElementById("previousResultsList"));
}
}
}
};
txtFile8.send(null);
The script parses a text file online:
http://www.drakedesign.co.uk/mdmarketing/uploads/date.txt
Which is updated weekly and has dates written in it like so:
19/04/16
12/04/16
...
My script separates the text document into each line and stores it as an array. A for loop is then used to show the dates on the screen in a column which looks like so:
The problem is that on clicking each date an alert box is not shown saying "hello" and there seems to be no response at all.
All help is greatly appreciated.
I solved the issue!!
The problem was that I had divs with opacity 0 that were overlaying my parentElement! sorry stupid mistake!

How to populate jqGrid filter toolbar and search when the page loads (ASP.net webforms)

Currently, I'm trying to populate the filterToolbar with values taken in from a cookie. If there is cookie data for the filters, I want it to fill the respective textboxes and filter the jqGrid for that data.
I'm using ASP.net webforms, so most of my data is initialized already. How/where could I add javascript in order to get this going?
I actually figured out what I was doing.
So what I ended up doing as a solution was adding a timeout function in the document.ready function
$(document).ready(function () {
// some code
setTimeout(function () {
$('#Jqgrid1')[0].triggerToolbar();
}, 500)
//some code
}
My guess is that I couldn't use the $('#grid')[0].toggleToolbar() to force it because whenever I tried to use it, it was before the whole grid was finish setting up.
In the ASP webform, I had several functions registered.
<cc1:JQGrid ID="Jqgrid1" runat="server"
Height="630"
SearchDialogSettings-Draggable="true"
EnableViewState="false"
AutoWidth="True" >
<ClientSideEvents
LoadComplete="Jqgrid1_LoadComplete"
GridInitialized="initGrid"
/>
<%-- grid code --%>
</cc1:JQGrid>
The LoadComplete is executed after the grid is loaded. I tried doing triggering my toolbar there, but didn't work. My guess is, again, it was too early in the grid execution to use the triggerToolbar() function.
The same went for the GridInitialized events (even though both events would seem to imply to me that the grid is done doing its thing... but whatever...)
The way that I read my cookies in was actually in the GridInitialized event handler.
function initGrid() {
var myJqGrid = $(this);
var valueName = 'GridFilters';
var myCookie = document.cookie;
var gridFilterString;
var gridFilterArray;
var currentFilter;
var myCookie_arr;
var myDic = {};
if (myCookie.indexOf(valueName) > -1) { // don't even bother if the cookie isn't there...
myCookie_arr = myCookie.split("; "); // looking for the cookie I need
// read cookies into an array
for (var i = 0; i < myCookie_arr.length; i++)
{
parts = myCookie_arr[i].split("=");
first = parts.shift(); // remove cookie name
myDic[first.trim()] = parts.join("=").trim(); // handles multiple equality expressions in one cookie
}
if (myDic.hasOwnProperty("GridFilters"))
gridFilterString = myDic["GridFilters"];
if (gridFilterString != "NONE") {
myFiltersDic = {}
myFiltersArr = gridFilterString.split("&")
for (var i = 0; i < myFiltersArr.length; i++) {
parts = myFiltersArr[i].split("=");
myFiltersDic[parts[0].trim()] = parts[1].trim();
}
myParams = $(this).jqGrid("getGridParam", "postData");
var filters = []
for (keys in myFiltersDic) {
$('#gs_' + keys.trim()).val(myFiltersDic[keys].trim());
}
$.cookie('m_blnSearchIsHidden', "0", "/");
if (!isLoaded)
{
$(this)[0].toggleToolbar();
}
isLoaded = true;
}
}
}

Help me simplify this JS code

I'm a beginner in JS and want to know a way to simplify this code. There are 7 different divs with iframes, and also 7 different links. I have shown 1 div with iframe and 1 link. I have no idea where to start. Any help would be greatly appreciated.
NOTE: The code works to my needs, but I just need to simplify it (less js code in html, and more in js file).
JavaScript in .js file:
function show_visibility(){
for(var i = 0,e = arguments.length;i < e;i++){
var myDiv = document.getElementById(arguments[i]).style;
myDiv.display = "block";}
}
function hide_visibility(){
for(var i = 0,e = arguments.length;i < e;i++){
var myDiv = document.getElementById(arguments[i]).style;
myDiv.display = "none";}
}
function refFrame() {
for(var i = 0,e = arguments.length;i < e;i++){
document.getElementById(arguments[i]).src = document.getElementById(arguments[i]).src;
}
}
Div/iframe to be modified:
<div id="r1-box">
<iframe id="frame-box1" class="work" src="youtubelink" width="720" height="405" frameborder="0"></iframe>
</div>
Link to execute JS:
<a id="r1" href="javascript:refFrame('frame-box2','frame-box3','frame-box4','frame-box5','frame-box6','frame-box7');show_visibility('r1-box');hide_visibility('r2-box','r3-box', 'r4-box','r5-box','r6-box','r7-box');">
</a>
As a beginner you shouldn't start using jQuery until you understand Javascript more.
There are a few ways you could simplify this, the most immediate one would be to get the Javascript out of the link and into a Javascript file, or at the top of the page:
window.onload = function() {
document.getElementById('#r1').onclick = function() {
refFrame('frame-box2','frame-box3','frame-box4','frame-box5','frame-box6','frame-box7');
show_visibility('r1-box');
hide_visibility('r2-box','r3-box', 'r4-box','r5-box','r6-box','r7-box');
};
// more...
};
window.onload is an event which fires once the page has - you guessed it - finished loading. There are better ways of doing this, but this is about as basic as it gets. I'd advise you look at javascript domready?
After looking at your code a bit more, I realised all your seven links will do essentially the same thing. You can simply this by using a single function:
function refClick(id) {
var i = 7,
frames = [],
boxes = [];
while(i--) {
if(i != id) {
frames.push('frame-box' + i);
boxes.push('r' + i + '-box');
}
}
refFrame.apply(null, frames);
hide_visibility.apply(null, boxes);
show_visibility('r' + id + '-box');
}
What I'm doing here is looping through 7 times, and building an array of arguments for the refFrame and hide_visibility functions. The id variable tells the loop not to put in that id into the arrays.
Using the .apply method, I can apply an array as the arguments and call it normally.
For each of your links, you can apply the following function
document.getElementById('#r1').onclick = function() {
refClick(1);
};
document.getElementById('#r2').onclick = function() {
refClick(2);
};
//.....
You could start using jQuery.
http://jquery.com/

Body onload in Javascript

I had written one JS in asp.net. I had called that from body onload, but the JS doesn't get called where I have put my debugger. What could be possible reasons for this? I'm developing website in dotnetnuke.
The JS I have written is syntactically and logically correct.
<script type="text/javascript">
var displayTime, speed, wait, banner1, banner2, link1, link2, bannerIndex, bannerLocations, bannerURLs;
function initVar() {
debugger;
displayTime = 10; // The amount of time each banner will be displayed in seconds.
speed = 5; // The speed at which the banners is moved (1 - 10, anything above 5 is not recommended).
wait = true;
banner1 = document.getElementById("banner1");
banner2 = document.getElementById("banner2");
//link1 = document.getElementById("link1");
//link2 = document.getElementById("link2");
//banner1 = document.getElementById("banner1");
//banner2 = document.getElementById("banner2");
banner1.style.left = 0;
banner2.style.left = 500;
bannerIndex = 1;
/* Important: In order for this script to work properly, please make sure that the banner graphic and the
URL associated with it have the same index in both, the bannerLocations and bannerURLs arrays.
Duplicate URLs are permitted. */
// Enter the location of the banner graphics in the array below.
//bannerLocations = new Array("internet-lg.gif","jupiterweb.gif","jupitermedia.gif");
bannerLocations = new Array("image00.jpg", "image01.jpg", "image02.jpg", "admin_ban.bmp");
// Enter the URL's to which the banners will link to in the array below.
bannerURLs = new Array("http://www.internet.com","http://www.jupiterweb.com","http://www.jupitermedia.com");
}
function moveBanner() {
//debugger;
if(!wait){
banner1.style.left = parseInt(banner1.style.left) - (speed * 5);
banner2.style.left = parseInt(banner2.style.left) - (speed * 5);
if(parseInt(banner1.style.left) <= -500){
banner1.style.left = 500;
bannerIndex = (bannerIndex < (bannerLocations.length - 1)) ? ++bannerIndex :0;
banner1.src = bannerLocations[bannerIndex];
//link1.href = bannerURLs[bannerIndex];
wait = true;
}
if(parseInt(banner2.style.left) <= -500){
banner2.style.left = 500;
bannerIndex = (bannerIndex < (bannerLocations.length - 1)) ? ++bannerIndex :0;
banner2.src = bannerLocations[bannerIndex];
//link2.href = bannerURLs[bannerIndex];
wait = true;
}
setTimeout("moveBanner()",100);
} else {
wait = false;
setTimeout("moveBanner()", displayTime * 1000);
}
}
</script>
REGISTRATION IN JS
<body onload="initVar(); moveBanner();">
</body>
I ran your code. Both methods executed without me having to make any modifications to the posted code. Is there possibly some other code that is overwriting the onload method?
The DotNetNuke best practice for binding to the "onload" property in JavaScript is to hook into JQuery's ready() method:
jQuery(document).ready( function() {
// put your code here
initVar();
moveBanner();
});
DotNetNuke 4.9.x and later ship with the jQuery JavaScript library included.
Have you edited DNN's Default.aspx? Otherwise, there isn't any way for you to have access to the body tag to add the onload attribute like you show.
How are you injecting this script? Are you using a Text/HTML module, are you using the Page Header Text setting for the page, are you adding it directly to the skin, have you written a custom module, or something else?
Instead of using the onload attribute on the body tag, I would suggest wiring up to that event in the script itself. If you're using any code to inject the script, you can ask DNN to register jQuery or a ScriptManager (for ASP.NET AJAX) so that you can use those libraries to wire the event up easily. If you can't guarantee that those are on the page, use the following:
function addLoadEvent(func) {
var oldonload = window.onload;
if (typeof window.onload != 'function') {
window.onload = func;
} else {
window.onload = function() {
if (oldonload) {
oldonload();
}
func();
}
}
}
addLoadEvent(function () {
initVar();
moveBanner();
});
I don't know much about asp.net but if you can put javascript code in your page, then you can try this alternative:
window.onload = function()
{
// any code here
}
This is the same as what you put in body tag.
The CSS left property takes a length, not an integer. You must have units for non-zero lengths. (Even when setting it using JavaScript!).

Categories

Resources