jquery replace the content of a div persistently - javascript

I am trying to replace the content of a div tag with a certain value every 50sec via polling and jQuery. And I would like to access the value of that updated div, so I can save a request to the backend.
My problem is that once the content has been replaced, the browser displays it correctly, however the HTML stays the same as the beginning. I'm afraid this is a rather basic question, but I'm really curious about this.
Here I prepared an example to illustrate the issue: http://jsfiddle.net/LJgN6/7/
And you can see it out ot JSfiddle's context to check the final HTML here: http://jsfiddle.net/LJgN6/7/show
I would like to achieve a way to have in the final HTML(i.e. right click, view page source):
num 1.1 replaced with num 1.2
num 2.1 replaced with num 2.2
...

The code that you see in the View Source window is the HTML that was sent to the browser before anything client side was allowed to modify the DOM. If you want to see the source as it is modified by your javascript, you need to inspect the DOM (IE F12, Firebug, etc.)
If you need to access this value that was inserted earlier, using javascript to access the contents of your element (ie. $('#number-2').text()) should return its contents as they are currently in the DOM.
EDIT: Corrected typo

It looks like you're already familiar with jQuery so I would go ahead and head over to the extremely helpful API and take a look at AJAX calls. There is plenty of documentation there that will help you.
http://api.jquery.com/jQuery.ajax/

Here's an idea. Take a look at my fiddle of your problem
$(document).ready(function(){
$('#number-1').html("num " + 1.1);
$('#number-2').html("num " + 2.2);
$('#number-3').html("num " + 3.3);
$('#number-4').html("num " + 4.4);
setInterval(function(){newInfo();}, 3000);
});
function newInfo(){
var firstDiv = $('#number-1');
var secDiv = $('#number-2');
var thdDiv = $('#number-3');
var frthDiv = $('#number-4');
var firstDivInfo = firstDiv.text().substr(4);
var secDivNewInfo = firstDiv.text().substr(4);
var thdDivNewInfo = secDiv.text().substr(4);
var frthDivNewInfo = thdDiv.text().substr(4);
var newNumber = (Math.random() + 1).toFixed(1);
secDiv.html("num " + secDivNewInfo);
thdDiv.html("num " + thdDivNewInfo);
frthDiv.html("num " + frthDivNewInfo);
firstDiv.html("num " + newNumber);
}

Related

Modifying CSS background-position by increment via javascript

Whereas I have plenty of experience with PHP coding, I am pretty new to using javascript so I hope this question doesn't come off as stupid.
My goal here is to create a button that when pressed causes the background-position in a defined DIV object to alter its background-position by one pixel.
I've been doing a lot of searching on Google as well as this site in particular and following the tips I have found I've been playing around with the javascript functions a lot but I can't seem to get one that works the way I need it.
My current incarnation looks like this:
<SCRIPT TYPE="text/javascript">
var xObject = 0; // Global
function xMinus(ele) {
xObject-=1;
document.getElementById(ele).css({ 'backgroundPosition': xObject + 'px ' + 0 + 'px' });
}
</SCRIPT>
Where the goal is upon clicking the button (containing onclick="javascript:xMinus('divID');" ) the background should shift to the left by one pixel.
However currently when I click it, Error Console gives me "Error: document.getElementById(ele).css is not a function".
I've tried a few different variations but always get similar results, or "Variable is not defined". Clearly I have no idea what I am doing. Please help! I am coding this for friends and do not want to keep them waiting too long.
If you are not using jQuery then,
document.getElementById(ele).style.backgroundPosition = xObject + 'px ' +'0px';
What are you passing inside the ele? It should be a string of the id of the element and it shouldn't start with a number.
Try rewriting the code this way:
var xObject = 0; // Global
function xMinus(ele) {
xObject--;
$('#'+ele).css({ 'backgroundPosition': xObject + 'px ' + 0 + 'px' });
}
I hope you are using jQuery! :) If not using jQuery, it should be:
document.getElementById(ele).style.backgroundPosition = xObject + 'px ' + '0';
And for the handler, that <a> tag, the code should be: (shouldn't contain javascript:)
BG Left Push!

JQuery hide/show gone wrong

Here is a simplified example of what i'm working with, working around preexisting code:
Basically I have 2 divs I want to hide/show in multiple places(stage 1, stage 2, stage 3,etc), as so:
var blue_div = "#Blue";
var red_div = "#Red";
var blue_stage = "#Blue" + count;
var red_stage = "#Red" + count;
Adding insult to injury the div's exist elsewhere on page and are hidden. Need to pull the content into another div for each stage. So i'm using .prepend() to grab the content, as so:
var blue_html = $(blue_div).html();
var new_div = "#new_div";
$(new_div).prepend(blue_html);
$(new_div).attr('id', blue_stage); //Changing the id based on the stage
That last part is really whats throwing me...As now I'm trying to use the new_div without first ending the script so it's not yet in the DOM...
if ($(blue_stage).is(':hidden')) {
$(blue_stage).show()
$("#cancel").bind("click",function(){
$(blue_stage).hide()
}
}
I've seen a lot done with Window setTimeout() as well as setinterval and .queue(). But my attempts have all failed. Hopefully my example wasn't confusing, any help at all is appreciated!
I think you can do something like this:
var $new_div = $('<div id="' + blue_stage + '"></div>');
which will allow you to edit the element directly so you can do things like:
$new_div.prepend(blue_html);
to change the id you do:
$new_div.attr('id', blue_stage)
and note when your setting the id like this you don't need the "#" as the other answer mentions
Remember that you use the hash-mark # when selecting, but when setting as an ID on a node, you just use the identifier without this mark. So this line:
$(new_div).attr('id', blue_stage); //Changing the id based on the stage
Equates to this:
$(new_div).attr('id', '#Blue' + count);
But should perhaps be like this:
$(new_div).attr('id', 'Blue' + count);
(without the hashmark).
Hopefully your problem is as easily solved! Good luck!

Using document.implementation.createDocument to create a new HTML document

I am being passed html as a string. My goal is to create a new document from the html that has all the appropriate nodes so that I can do things like call doc.getElementsByTagName on the doc I create and have it work as expected. An example of my code is here.
var doc = window.document.implementation.createDocument
('http://www.w3.org/1999/xhtml', 'html', null);
doc.getElementsByTagName('html')[0].innerHTML =
'<head><script>somejs</script>' +
'<script>var x = 5; var y = 2; var foo = x + y;</script>' +
'</head><body></body>';
var scripts = doc.getElementsByTagName('script');
console.log(scripts[0] + " code = " + scripts[0].innerHTML);
I am having the following issues:
If something inside a script tag contains a character like < (eg in the example above in the "var foo = x + y;" statement change the + to a < symbol), I get an INVALID_STATE_ERR: DOM Exception 11.
Even if nothing inside the script tag uses such characters, when I run the above I get the output "[object Element] code =undefined"
So my questions are:
A. How do I handle characters such as < that give DOM Exception 11 when I try to use them in whatever I am setting the innerHTML to
B. How do I make the document properly parse the script tags and put their code into their innerHTML attribute so that I can later read it.
EDIT: As Ryan P pointed out this code actually works in FF. So if anyone could help me get it working in chrome that would be much appreciated!
Taken from https://github.com/rails/turbolinks,
why dont you try to create the document this way:
doc = document.implementation.createHTMLDocument("");
doc.open("replace");
doc.write(html);
doc.close();
where the html should be your html contents.
I havent tested it and dont know if you should escape characters first.
A. You need to convert any < to an HTML entity (<). The rules don't cease to apply just cause you're in a script tag.
B. You call your variable 'doc' but try to get the script tags from an undefined variable 'tempDoc'. When I run your code in my browser after changing that variable, it all seems to work fine.

Sending <script> tags in ajax content

I'm working on porting this lab: http://www.cis.syr.edu/~wedu/seed/Labs/Attacks_XSS/XSS.pdf
For a project. First, however, I have to be able to complete it myself. I'm trying to work out the self-propogating worm, and having some difficulties. How can I send a script tag through the content? If I try:
var wormCode = getElementById("worm");
var escapedWorm = escape(wormCode.innerHTML);
content="topicTitle=testprop&postText=<script>"+escapedWorm+"</script>&forum=3&action=ptopic";
Ajax.send(content);
The tag breaks out of the larger javascript this sits in. I've also tried splitting it up as :
...+"</scr"+"ipt>&...
but this did not work.
Any tips?
edit: updated with my more recent (and I hope, accurate) attempts.
var wormCode = getElementById("worm");
var escapedWorm = escape("<" + "script>" + wormCode.innerHTML + "</" + "script>");
content="topicTitle=testprop&forum=3&action=ptopic&postText="+escapedWorm;
Ajax.send(content);
You aren't escaping the script tags.
Splitting up the the end script tag into two different parts ended up working after all. I think that the issues I was having with it were browser-specific.

jQuery- .css() not working for an input

This should be a really simple problem, but I can't quite figure out what I am doing wrong. I am trying to access the CSS property 'border-bottom' like this:
var temp = $('#divName').css('border-bottom');
Unfortunately, after this, temp contains the string ""
Does anyone know why this is not working or what I should do differently to make it function? Thanks.
The styles have to be more specific. Since border-bottom is a short-property for other properties (similar to background, to name a common one), the property has to be explicitly given.
var elem = $('#divName');
var border_width = elem.css('border-bottom-width');
var border_color = elem.css('border-bottom-color');
var border_style = elem.css('border-bottom-style');
var border_bottom = border_width + " " + border_color + " " + border_style;
Fiddle: http://jsfiddle.net/6wRj4/
See also: MDN: border-bottom short-hand.
Check to ensure that $('#divName') does select a single element. You can use array syntax on a jquery object to get back the underlying DOM object. You should also check (for example, using Firebug) to make sure that the DOM element you're looking at does have the style that you're looking for.
If both of those things are working correctly, you might try using the more granular border properties... border-bottom-style, border-bottom-width, etc.
Try with document.getElementById("divName").style.borderBottom;.

Categories

Resources