I want to refresh an img element within a div every 5 seconds that would indicate whether the user is connected to the internet or not connected. If the user is connected, it will display an image online, but if the user is offline, a local image will display.
However, I cannot get around this quote problem. I even tried the "&-quot;" thing (without the dash) and it still will not work. Here is the code:
<script type="text/javascript">
window.setInterval("refreshDiv()", 5000);
function refreshDiv(){
document.getElementById("test").innerHTML = "<img id="this" src="http://stallionware.weebly.com/uploads/3/0/4/3/30431988/4901948_orig.png" onerror="this.src='nowifi.png'">";
}
</script>
<div id=wifi>
<img id="this" src="http://stallionware.weebly.com/uploads/3/0/4/3/30431988/4901948_orig.png" onerror="this.src='nowifi.png'">
</div>
I do not have the desire to use jQuery or Ajax or any server-side languages because this is all on a local machine.
You can escape those double quotes like this:
document.getElementById("this").innerHTML = "<img id=\"this\" src=\"http://stallionware.weebly.com/uploads/3/0/4/3/30431988/4901948_orig.png\" onerror=\"this.src='nowifi.png'\">";
By typing \" you're telling the JavaScript that you want to insert a double quote inside your string. The other option you have is to use single quotes instead. (I've changed your getElementById from 'test' to 'this' since your HTML has no 'test' as Id)
Also, you shouldn't call a function using a string as you did on refreshDiv. Instead you should call its name like this:
window.setInterval(refreshDiv, 5000);
You should use a hierarchy of single quotes and double quotes. Using double quotes under double quotes makes the JS think is a combination of strings. But it fails without the operators.
<script type="text/javascript">
window.setInterval("refreshDiv()", 5000);
function refreshDiv(){
document.getElementById("test").innerHTML = '<img id="this" src="http://stallionware.weebly.com/uploads/3/0/4/3/30431988/4901948_orig.png" onerror="this.src='nowifi.png'">';
}
</script>
<div id=wifi>
<img id="this" src="http://stallionware.weebly.com/uploads/3/0/4/3/30431988/4901948_orig.png" onerror="this.src='nowifi.png'">
</div>
Apart from that rather than checking every 5 seconds I would suggest going and using online and offline events of browser - which then saves your code from having setInterval kind of stuff.
In JavaScript, you can use single-quotes or double-quotes. For your case, you should put the string containing the div in single-quotes and have the HTML attributes within that string using double-quotes. However, it looks like you have a few other mistakes in your code anyway. Try this:
<img id="image" src="http://stallionware.weebly.com/uploads/3/0/4/3/30431988/4901948_orig.png" onerror="error">
with the following in your Javascript:
var theImage = document.getElementById('image');
function error() {
theImage.src='nowifi.png';
}
function refreshDiv(){
theImage.innerHTML = '<img id="image" src="http://stallionware.weebly.com/uploads/3/0/4/3/30431988/4901948_orig.png"
onerror="error">';
}
setInterval(refreshDiv, 5000);
Related
I have hundreds of HTML pages and I would like to add a new div with link and style to them but editing each page takes lots of time.
All the pages have one common JavaScript file.
how can I append or add below div to all the pages?
<div style="background-color:#561D1B;" id="testid">
<marquee style="background-color:#561D1B;height:19px;"><script src="https://testurl.com/test" type="text/javascript" ></script></marquee>
</div>
avoid-fout is a class and I tried to add below code but it's not working.
$(".avoid-fout").append("<div style="background-color:#561D1B;" id="testid">
<marquee style="background-color:#561D1B;height:19px;"><script src="https://testurl.com/test" type="text/javascript" ></script></marquee>
</div>");
When appending, make sure you observe the use of single and double quotes, as shown below
$(".avoid-fout").append('<div style="background-color:#561D1B;" id="testid">
<marquee style="background-color:#561D1B;height:19px;"><script src="https://testurl.com/test" type="text/javascript" ></script></marquee>
</div>');
Use single quote first, then everything inside should be done with double quotes, or vice versa.
Try this
$(".avoid-fout").append(`<div style="background-color:#561D1B;" id="testid"> <marquee style="background-color:#561D1B;height:19px;"><script src="https://testurl.com/test" type="text/javascript" ></script></marquee>
</div>`);
Also make sure, your script src is a valid JS
Your .append call will not work because you are appending a string with double quotes, and also using double-quotes in the html. Simplest fix is to use single quotes for your html string instead:
$(".avoid-fout").append('<div style="background-color:#561D1B;" id="testid">
<marquee style="background-color:#561D1B;height:19px;"><script src="https://testurl.com/test" type="text/javascript" ></script></marquee>
</div>');`
If you do not want to use Jquery or avoid inserting HTML string, this might help. It uses vanilla JS dom APIs. You can modify the method appendToElem in case you need to add any other stuff
function appendToElem(elem) {
if (!elem) {
console.error(elem)
}
var script = document.createElement('script')
script.setAttribute("src", "https://testurl.com/test")
script.setAttribute("type", "text/javascript")
var marquee = document.createElement('marquee')
marquee.style.backgroundColor = "#561D1B"
marquee.style.height = "19px"
marquee.appendChild(script)
var div = document.createElement("div")
div.id = "testid"
div.style.backgroundColor = "#561D1B"
div.appendChild(marquee)
elem.appendChild(div)
}
appendToElem(document.getElementsByClassName('avoid-fout')[1])
<div class="avoid-fout">
<h2>Some Random title</h2>
<p>Some Text</p>
</div>
<div class="avoid-fout">
<h2>Add At the end of this container</h2>
<p>
Add the asked div, with marquee and script below this.
</p>
</div>
There are a couple of problems. You are trying to use double-quotes inside of a double quoted string, you can't do that without escaping the double quotes.
"This is "not" a valid string";
"This \"is\" a valid string";
A simple solution to this that I usually use is to just use single quotes to encapsulate HTML and only use double-quotes in my HTML:
'<div id="double-quotes-work-here">Just can\'t use unescaped single-quotes</div>';
The other problem is that you are trying to use a string that spans multiple lines. Single and double quoted strings in JS can generally not include any new line characters. In cases like this where you are just inserting HTML and the new lines don't actually matter, the easiest thing to do would be to just delete the new lines and include all the HTML on one line:
$(".avoid-fout").append('<div style="background-color:#561D1B;" id="testid"> <marquee style="background-color:#561D1B;height:19px;">Foo</marquee> </div>');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="avoid-fout"></div>
If you want to keep it on multiple lines, there are a few options.
You could use multiple concatenated strings:
$(".avoid-fout").append('<div style="background-color:#561D1B;" id="testid">' +
'<marquee style="background-color:#561D1B;height:19px;">Foo</marquee>' +
'</div>');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="avoid-fout"></div>
Or you could escape the new-lines by using \:
$(".avoid-fout").append('<div style="background-color:#561D1B;" id="testid">\
<marquee style="background-color:#561D1B;height:19px;">Foo</marquee>\
</div>');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="avoid-fout"></div>
This way should be avoided though. It is fairly error-prone, if there is any white space after the \, it will cause a syntax error; one that is really hard to notice since the white space is not visible. For instance:
'this is a valid\
multi-line string';
'this is not a valid\
multi-line string';
See the difference? Me neither.
If the browsers you are targeting all support it (most modern browser do), I would use a template literal:
$(".avoid-fout").append(`<div style="background-color:#561D1B;" id="testid">
<marquee style="background-color:#561D1B;height:19px;">Foo</marquee>
</div>`);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="avoid-fout"></div>
Template literals allow you to use multi-line strings without any escaping, you can use both single and double quotes inside of them without escaping them. They also allow you to do other neat things like expression interpolation and using tagged templates.
Learning to use the developer console in your browser, as well as a linter, such as jsHint can help a lot with spotting errors like these.
Who would think so, but I actually need 3 levels of nested quotes in an ASP.NET WebForms page.
Here's what I have:
<img
src='<% ResolveClientUrl("~/SwissStyleguide/img/swiss.svg"); %>'
onerror="this.onerror=null; this.src='SwissStyleguide/img/swiss.png';"
alt="Confederatio Helvetica"
/>
Now, the first part, assigning a dynamically created URL to the src attribute works fine. The server resolves the given special URL and creates an absolute link for the client to fetch.
But the onerror handler is more tricky: since the src URL to the png image is already in an expression with double quotes, I can not invoke the ASP.NET ResolveClientUrl method, which strictly requires double quotes for the string argument.
I tried to do it like this (does not work!)
<img
src='<% ResolveClientUrl("~/SwissStyleguide/img/swiss.svg"); %>'
onerror="this.onerror=null; this.src='<% ResolveClientUrl("~/SwissStyleguide/img/swiss.png"); %>';"
alt="Confederatio Helvetica"
/>
But without much surprise, Visual Studio complains about this string. The only idea that comes to my mind is to use a string constant to avoid having the innermost quotes, but that seems very ugly.
Is there a way to escape or otherwise specify some or all of the quotes to make that work?
Note: I know about this question: When to use double or single quotes in JavaScript? but changing the quotes does not help in this case.
Well,... this turned out as an instance of the "<%$, <%#, <%=, <%# … what's the deal?" WebForms problem, answered perfectly here: https://stackoverflow.com/a/957321/79485
The solution is to use the equal sign after the percent sign and omit the trailing semicolon. Like this:
onerror="this.onerror=null; this.src='<%= ResolveClientUrl("~/SwissStyleguide/img/swiss.png") %>';"
I'll leave the question and this answer here as a reminder of anyone tripping over this too.
How about placing the attributes from the code-behind instead?
.aspx
<img id="image" runat="server" alt="Confederatio Helvetica" />
.aspx.cs (Page_Load)
image.Attributes.Add("src", Page.ResolveUrl("~/SwissStyleguide/img/swiss.svg"));
image.Attributes.Add("onerror", "this.onerror=null; this.src='" +
Page.ResolveUrl("~/SwissStyleguide/img/swiss.png") + "';";
I want to create a list of news on my webpage. When mouse click on the content, there will be a url available. For example apple news
Here are my sample codes, my problem is: when I try to add a variable's value into the href, like href="www.search.com?keyword="+var.keyword, it will display apple news
Actually there are a 50 objects in the variable model, so it will having 50 model.link and model.keywords, please help me to change the sample code which works on w3cshools.com "try it youself". I tried 10 times by really don't know the how to fix it, thanks!
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
<!-- should end this tag-->
var model=[{"link":"http://www.google.com?keyword=","keyword":"apple" "content":"This is a news"}]
<!-- miss a ";" at the end of line -->
</script>
<script>
$(document).ready(function(){
$("p").html("Click <a href=model.link+model.keyword>this link</a>");
<!--Finally this works: $("p").html("Click <a href='"+model[0].link+model[0].keyword+"'>this link</a>");-->
});
</script>
</head>
<body>
<p>A content</p>
</body>
</html>
Quote properly:
$("p").html("Click this link");
you missed comma in your model variable::
var model=[
{
"link":"http://www.google.com?keyword=",
"keyword":"apple",
"content":"This is a news"
}
];
And since its array of object , you need to access it like model[0].link to get first object from model array, like:
$(document).ready(function(){
$("p").html("Click <a href='"+model[0].link+model[0].keyword+"'>this link</a>");
});
Put the link correctly
$("p").html("Click <a href='"+model.link+model.keyword+"'>this link</a>");
This is what you need:
var model=[ { link:'http://www.google.com?keyword=', keyword: 'apple', content: 'This is a news'} ];
$.each( model, function( key, value ) {
$('p').append('Click this link');
});
You need to loop through the array of objects and get values. You can use $.each to make this easy since you are using jQuery though you can just as easily do this with vanilla Javascript, I would also get in to the practice of wrapping strings in single quotes in Javascript, that way you can add double quotes in a nice readable syntax to HTML strings you will be adding to the DOM.
Note that I did not use quotes for object keywords too.
See fiddle:
http://jsfiddle.net/r8MQ9/1/
Background:
I have string of html with about 10 image tags that passes through some JavaScript as a string at runtime before being injected into a containing element. The data-thumb tag of each image is slightly incorrect and needs to be altered before making it into the DOM. Here is an example:
<img src="foo_lg_db.jpg" data-large="foo_lg_db.jpg" />
<img src="bar_lg_db.jpg" data-large="bar_lg_db.jpg" />
<img src="fizz_lg_db.jpg" data-large="fizz_lg_db.jpg" />
Needs to become:
<img src="foo_tn_db.jpg" data-large="foo_lg_db.jpg" />
<img src="bar_tn_db.jpg" data-large="bar_lg_db.jpg" />
<img src="fizz_tn_db.jpg" data-large="fizz_lg_db.jpg" />
Question:
In JavaScript (jQuery is OK), how do I achieve this search and replace?
THE ANSWER:
Thanks to Mark's answer I learned that it is possible to instantiate a jQuery object before it hits the DOM so, rather than using regex, I did something like this:
var stringHtml = "<img . . .";
var div = $("<div>").html(stringHtml );
$.each(div.find('img[src]'), function () {
$(this).attr('src', $(this).attr('src').replace('_lg', ''));
});
return div.html();
$('img[data-thumb]').each(function() {
$(this).attr('data-thumb', $(this).attr('data-thumb').replace('_lg_','_tn_'));
});
Something like that in jQuery.
Sounds like a problem you should be fixing server-side if possible though.
If you give jQuery an HTML element like $('<div>') it will essentially create the HTML element for you and then you can manipulate it before inserting it into your DOM. I don't know if it will handle multiple elements, but you can create a container first (like above) and then set the content like so
$('<div>').html(yourHtml).find('img[data-thumb'])./* code above */
I have some html code rendered on the server side. This is passed to a jsp which renders a javascript-call with this html:
<script type="text/javascript">
window.parent.${param.popup_return}("${helpId}", "${content}");
</script>
content is like
"
This is a <p class="xyz">test</p>
"
My problem is that - according to the quotes in 'content' - the javascript-call is wrong as it is rendered to
<script type="text/javascript">
window.parent.${param.popup_return}("ybc", "This is a <p class="xyz">test</p>");
</script>
Does anyone know how I can solve this (besides manually replacing all quotes)?
Use a JSON encoder to create the encoded strings.
But you'll also have to ensure that the output doesn't contain the sequence </ in string literals, which is invalid in a <script> block (</script is the version that will also break browsers).
Many JSON encoders either by default or optionally will encode to <\/ or \u003C/ to avoid this problem.
I use this:
<div id="result" style="display:none">
${content}
</div>
<script type="text/javascript">
window.parent.${param.popup_return}("${helpId}", dojo.byId("result").innerHTML);
</script>
This seems to work perfectly
You aren't using JSTL here (you originally tagged the question with only JSTL). You are using EL in template text. It get printed plain as-is. You'd like to use JSTL core <c:out> to escape predefined XML entities (which also works for HTML in this particular case, quotes is among the escaped XML entities).
window.parent.${param.popup_return}("<c:out value="${helpId}" />", "<c:out value="${content}" />");
An alternative (if you hate that the JSP syntax highlighter or validator bugs/jerks about nested tags/quotes) is the JSTL function fn:escapeXml():
window.parent.${param.popup_return}("${fn:escapeXml(helpId)}", "${fn:escapeXml(content)}");
Have you tried using single quotes instead of double quotes? i.e. changing "${content}" to '${content}'