punctuation marks in javascript - javascript

can you guys plese help me to correct the punctuation marks in the javascript below? Found error when i paste in visual studio. I'm not familiar with javascript! Thanks guy...
function showLocalImage(imgname) {
imgname = imgname.replace(/\\/g,”/”);
imgname = imgname.replace(/\’/g,”\\’”);
content = “<img src=\”" + String(imgname) + “\” border=\”0\” height=\”150\” weight=\”150\”>”;
eval(‘document.getElementById(“imagepreview”).innerHTML=\” + content +”‘”);
document.getElementById.imagepreview.style.visibility =’visible’;
}

This is because some of your quote characters are actually from a different character encoding, Use the following code:
function showLocalImage(imgname) {
imgname = imgname.replace(/\\/g,"/");
imgname = imgname.replace(/\’/g,"\\'");
content = "<img src=\"" + imgname + "\" border=\"0\" height=\"150\" weight=\"150\">";
var image_preview = document.getElementById("imagepreview");
image_preview.innerHTML = content;
image_preview.style.visibility = 'visible';
}
A couple of things:
You should reuse DOM result sets and elements as much as possible to avoid having to run a query against the DOM every time you need to reference an element or set of elements.
You should really try to avoid using the eval function as much as possible.
eval == EVIL

You seem to use wrong quote characters (” or ‘). Replace them with " or ' and you'll be good. Use an ascii text editor, not a word processor for typing.

You should avoid eval, and declare the content variable, as well as declare a reference to the imagepreview element:
function showLocalImage(imgname) {
imgname = imgname.replace(/\\/g,"/");
imgname = imgname.replace(/\'/g,"\\'"); //Is this really necessary?
var content = "<img src=\"" + imgname + "\" border=\"0\" height=\"150\" weight=\"150\">";
var img = document.getElementById("imagepreview");
img.innerHTML = content;
img.style.visibility ='visible';
}

Related

Javascript var in string

So I have this code and would like to know how I could go ahead to put my javascript var into this string. I cannot seem to make a working code for myself.
For the image source i want picture.value to be in there. I have tried different solutions but have not managed to work it out myself. All help is greatly appreciated
var text = "<img src="">
I have currently been trying var text = "<img src=" + picture.value +">
but that doesn't seem to work for me.
You cannot use " & ' this together unless you escape it with a \.
var text = '<img src="' + picture.value + '">'
OR
var text = "<img src=\"" + "Hi" + "\">"
Try using ES6 new feature called Template literals (using quote). It is more cleaner and simpler.
var picture = {'value':'test-src-location'};
var text = `<img src="${ picture.value }">`;
console.log(text);
Assuming your picture.value is not empty.
var text = '<img src=' + picture.value + '>';
Example: https://jsfiddle.net/no293etL/

Javascript function isn't recognized

I don't have many knowlege in javascript so I don't know what is the problem here,
I create divs dynamically in js and each div call a function when is clicked but the function is not recongized. This is part of the code
for (......) {
var listatema = document.createElement("div");
listatema.innerHTML += "<a href='javascript: void(0)' onClick='functest(" + pag + ")'>" + temat + "</a>";
document.getElementById('menu').appendChild(listatema);}
}
"tema" is a text, the function "functest" has an argument "pag[aux]", this is a number.
The function is:
function functest(arg){
console.log(arg)
}
other alternative that i tried is change that: onClick='"+ functest(pag) +"':
i change the position of Quotation marks "" and the function work good but it is executed when the page is loaded, it don't wait to do click.
Your code should work if you're doing something like:
function functest(arg) {
console.log(arg);
}
for (var i = 0; i < 10; i++) {
var listatema = document.createElement("div");
listatema.innerHTML += "<a href='javascript: void(0)' onClick='functest(" + i + ")'>" + i + "</a>";
document.getElementById('menu').appendChild(listatema);
}
<div id="menu"></div>
I would, however, recommend using addEventListener or setting the onClick handler on the document element object rather than setting the innerHTML. Note that setting innerHTML is not advised, especially when rendering user input. See https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML#Security_considerations. In your case, it probably isn't really an issue, but it's good practice to avoid it if you can :)
for (var i = 0; i < 5; i++) {
var wrapper = document.createElement("div");
var listatema = document.createElement("a");
listatema.textContent = i;
listatema.href = "javascript:void(0)";
listatema.addEventListener('click', function(e) {
console.log(this.i);
}.bind({ i : i }));
wrapper.appendChild(listatema);
document.getElementById('menu').appendChild(wrapper);
}
<div id="menu"></div>
onClick='functest(\""+ pag +"\")'
you forgot to quote the parameter.

generate image tags in html for each object of an array in Javascript

I know my question might seem stupid but I am stuck with this bit of code and I struggle with Javascript.
I would like to be able to display inside my page some images from the text of some links.
It might appear twisted but this is exactly what I want to do :-)
This is what I have managed to sort out so far if that can give you an idea :
http://www.online-image-editor.com/styles/2013/images/example_image.png
http://images.math.cnrs.fr/IMG/png/section8-image.png
http://www.online-image-editor.com/styles/2013/images/example_image.png
var liens = document.getElementsByTagName('a'),
valeurs = [];
for (i = 0; i < liens.length; i += 1) {
if (liens[i].text) {
valeurs.push(liens[i].text);
document.body.innerHTML = "<img src='" + valeurs[i] + "'>";
}
}
Thank you!
Well, you're almost there. The most trivial fix for your code is to change this line:
document.body.innerHTML = "<img src='" + valeurs[i] + "'>";
into this:
document.body.innerHTML += "<img src='" + valeurs[i] + "'>";
This will append to innerHTML instead of overwritng it.
A slightly better solution would be to actually create DOM nodes instead of modifying innerHTML. So the above line could be replaced by:
var img = document.createElement('img');
img.src = valeurs[i];
document.body.appendChild(img);
You can check it out here

li append function not work

I'm using blogger as my blogging platform. In my blog homepage, I create a function to grab all images from single post for each post (there are 5 posts in my homepage), then append all images from single post to single slider, for each post.
This is my function script (I place it after <body> tag):
<script type='text/javascript'>
//<![CDATA[
function stripTags(s, n) {
return s.replace(/<.*?>/ig, "")
.split(/\s+/)
.slice(0, n - 1)
.join(" ")
}
function rm(a) {
var p = document.getElementById(a);
img = p.getElementsByTagName("img").each( function(){
$(".flexslider .slides").append($("<li>").append(this));
});
p.innerHTML = '<div class="entry-container"><div class="entry-content"><div class="entry-image"><div class='flexslider'><ul class='slides'></ul></div></div><div class="entry-header"><h1>' + x + '</h1></div><p>' + stripTags(p.innerHTML, SNIPPET_COUNT) + '</p></div></div>'
}
//]]>
</script>
Then my variable, each post have single variable, different for each post based on it's ID:
<script type='text/javascript'>var x="Post Title",y="http://myblog.url/post-url.html";rm("p8304387062855771110")
My single post markup:
<span id='p8304387062855771110'></span>
The problem is, the append function in my script not work. Am I forget something in my code?
Your jQuery/JavaScript is very ropey. There is no method each on a nodelist. Try not to mix jQuery/JavaScript up so much. And you might consider using a array/join on the html you want to insert to keep the line length readable. That way you might have noticed that your HTML quotes were not consistent.1
var $p = $('#' + a);
$p.find('img').each(function () {
var html = $('<li>').append($(this))
$('.flexslider .slides').append(html);
});
var html = [
'<div class="entry-container"><div class="entry-content">',
'<div class="entry-image"><div class="flexslider">',
'<ul class="slides"></ul></div></div><div class="entry-header">',
'<h1><a href="',
y,
'">',
x,
'</a></h1></div><p>',
stripTags(p.innerHTML, SNIPPET_COUNT),
'</p></div></div>'
].join('');
$p.html(html);
1 Personally I prefer single quotes for JS work and double quotes for HTML attributes and never the twain shall meet.
I think <li> doesnt work try li like this:
$(".flexslider .slides").append($("li").append(this));
You could get rid of type="text/javascript" and //<![CDATA[, it is 2014, after all ;-)
Also, .*? is not what you mean.
<script>
function stripTags(s, n) {
return s.replace(/<[^>]*>/g, "") // Be careful with .*? : it is not correct
.split(/\s+/)
.slice(0, n - 1)
.join(" ")
}
function rm(id) {
var $p = $('#' + id);
img = $p.find("img").each( function(){
$(".flexslider .slides").append($("<li>").append(this));
});
p.innerHTML = '<div class="entry-container"><div class="entry-content"><div class="entry-image"><div class="flexslider"><ul class="slides"></ul></div></div><div class="entry-header"><h1>' + x + '</h1></div><p>' + stripTags(p.innerHTML, SNIPPET_COUNT) + '</p></div></div>'
}
</script>

How can I pass a variable through an onclick event when javascript is creating the html?

My javascript creates a line of html.
That html has an onclick event call to openSingle().
I need to pass a variable into that function.
onclick="openSingle('+findID+')"
When I check the dev panel when it runs, i get
onclick="openSingle(WP0100200-3a)"
The only thing that is missing is the quotes around the id.
But if i try to code in the quotes, it breaks the html and then puts everything out of order.
Here is my line of code and all the pertaining variables.
var iconImage = '<img src="../../resources/images/annotation-icon.png" style="float:left; margin-left:20px; margin-right:0px;"onclick="openSingle('+findID+')"/>';
var paragraph = '<p id="Manual-para" class="colorMe"><a href="';
var redirect = linkMe + '#' + findID;
var manName = section.childNodes( x ).getAttribute( "manualName" );
var workPack = section.childNodes( x ).getAttribute( "workPacket" );
document.getElementById( "annotateBody" ).innerHTML += iconImage + paragraph + redirect + '">' + annotationTitle + ' - ' + manName + ' - ' + workPack + '</a></p>';
You can escape quotes with a backslash like so
var iconImage = '<img src="../../resources/images/annotation-icon.png" style="float:left; margin-left:20px; margin-right:0px;"onclick="openSingle(\''+findID+'\')"/>';
and as other comments suggested you should ideally avoid inline Javascript
Escape the single quotes, like this:
var iconImage = '<img src="../../resources/images/annotation-icon.png" style="float:left; margin-left:20px; margin-right:0px;"onclick="openSingle(\''+findID+'\')"/>';
try adding \' will fix the problem
var iconImage = '<img src="../../resources/images/annotation-icon.png" style="float:left; margin-left:20px; margin-right:0px;"onclick="openSingle(\''+findID+'\;)"/>';
Here is the answer: with escaping character \ for ' character
var iconImage = '<img src="../../resources/images/annotation-icon.png" style="float:left; margin-left:20px; margin-right:0px;"onclick="openSingle(\''+findID+'\;)"/>';
Also try concating ‘and’
One thing you could try doing is attach the onclick after you create the DOM node. This lets you be as flexible as you want and avoids having to eval strings and other things like that.
var domnode = /* get the image tag */
domnode.onclick = function(){ openSingle(findId) }

Categories

Resources