JS Events help - when changing a style property - javascript

I have a code here that i was supposed to make to change a style property, managed to make it work, but had to look up at the proper way to place the ', the " and the + .
document.getElementById('image').style.backgroundImage="url('" + element.src + "')";
I have no issue understanding how structurally this works, my only question resides on why of the extra ', extra " and extra + inside where you call for the element.src.
originally i did something like this, and it obviously didnt work, why did those ('" + and + "') make the code work...
any help is appreciated
cheers
document.getElementById('image').style.backgroundImage="url(' element.src ')";

Let's analyze everything from your first code segment and that should give you a better understanding:
document.getElementById('image').style.backgroundImage="url('" + element.src + "')";
document is a variable
getElementById is a function, with the string 'image' being a parameter for that function.
style is a property
backgroundImage is a property which must be and must take a string
"url('" is a string
element is a variable, an object in this case, with src being one of its properties.
"')" is a string
The + signs are used to concatenate the string formed from "url('", element.src and "')". In short you are saying, "make a string from "url('", element.src and "')" and assign that string to the property backgroundImage.
Whereas in this:
document.getElementById('image').style.backgroundImage="url(' element.src ')";
The browser has no idea that element.src is a variable and not part of the string, since you enclosed it int double quotes, signaling that everything between the quotes is a string.

element is a variable outside of a string literal, but inside a string literal it is just the word element.
const element = "Hello!";
const first = "start element end";
const second = "start " + element + " end";
console.log({first,second});

Inside of CSS, you have to put your URL inside of quotes or apostrophes, so that has to translate to the javascript as well.
When you call the DOM event it will do this:
Original tag:
<div src="http://example.com/image.png"></div>
after calling the javascript function:
<div style="background-image: url('http://example.com/image.png');" src="http://example.com/image.png"></div>
and because you need to have some sort of quotation in the URL syntax, you have to use a different kind of quotation, such as the '' in this case.
For more reference on the background image style, you can go here: https://www.w3schools.com/css/css_background_image.asp
but to completely answer your question, the + in there is used to say that you want to add something else there, such as another string or a variable.
More information on that here: https://www.w3schools.com/jsref/jsref_operators.asp (you have to scroll down a bit to the string operators section).

Related

issue passing a value to a function

EDIT: the 'more' link is built from here:
document.getElementById("elenco_fiveboard").insertAdjacentHTML('beforeend',
"<li>" +
"Titolo: " + valore_comando + " " +
"(<a href='javascript:getInfo("+ valore_comando +");'>" +
"more" + "</a>)" +
"</li>");
So I have to wrap valore_comando with hyphens but I get error trying to write
"(<a href='javascript:getInfo(""+ valore_comando +"");'>" +
or
"(<a href='javascript:getInfo('"+ valore_comando +"');'>" +
Sorry but I am not so strong with JS syntax and I am starting from some code that is not my own.
I have this simple JS function:
getInfo = function(title){
worker.port.postMessage("maggiori_informazioni:" + title);
}
I run it passing to the variable title a value but I always get an error. If title is 'example' then JS try to run
getInfo = function(example)
and I get the error:
Reference Error: example is not defined.
If title has more than one word: 'first example'
then JS will try to run
getInfo = function(first example)
and I get the error:
Syntax error: missing ) after argument list (looking for parentesys
after 'first').
What am I missing here??
This code is part of my first test with webSockets. If you want to see the full code you can open this index page and put a value on the first alert you see. That value is the title that you will see on the dashboard page.
The error can be reproduced trying to hit 'More' after each defined title in dashboard.
Sorry for italian in the site but it's a user requirement.
getInfo having reference to your function. So you can call this by:
getInfo(value);
Use quotes if you are passing string value and if you are passing
integer value you can simply pass.
For instance:
getInfo("Message Title"); //string
getInfo(3); // Integer
DEMO
You can also call like this:
getInfo = function(title){
alert("maggiori_informazioni:" + title);
}("String");
DEMO
Updates:
You can use this:
"(<a href='"+getInfo(valore_comando)+";'>" +
the function has been assigned to getInfo so please call getInfo()
string should be enclosed with ''
So the code should be
getInfo('example')
You're going to have to escape some quotation marks.
"(<a href=\"javascript:getInfo('"+ valore_comando +"');\">" +
The \ character before the quotation marks for the href attribute tells the JavaScript parser that they're part of the string instead of the beginning or end of a string.
The problem is that example is not defined. If you wanted to call the function with example as input it needs either single quotes or double quotes around it. "example" or 'example'.
getInfo("example"); // Works as intended
Another option is to create a variable containing the string, and pass that to the function.
var myVariable = "example";
getInfo(myVariable); // Still works, myVariable is a string with value "example"

Single quote or double quote in javascript

I always see a write style in javascript but I don't know why code like this.
For example, I have a variable.
var topic = "community";
And when I learned javascript I saw someone coded in jQuery like this, some code in section.
:contains("' + topic + '")
But I think it can code just like this.
:contains(topic)
Or
:contains("topic")
What the differences between above three ?
:contains("topic")
this search for elements that contains "topic" string
where as
var topic = "community";
:contains(topic)
topic here becomes "community"..so it searchs for element that contains "community";
well for this
:contains("' + topic + '")
i guess the code is incomplete..
$('div:contains("' + topic + '")')..; //div for example sake
this becomes
$('div:contains("community")')..; //<-- just to make sure the string is encoded with `""`
:contains("' + topic + '") will look for the string '(VALUE of topic)', including the single quotes.
:contains(topic)
will look for the value of topic, with no surrounding quotes.
:contains("topic")
will look for literally topic.
There is no difference between single quotes and double quotes, both are used to mark an element as a string.
var s = "hello"
var m = 'hello'
m === s // true
the other example refers to escaping a string, in the case of:
contains("' + topic + '")
topic actually references a variable and not a string, therefore the quotes must be escaped in order for the program to get access to the value of the variable. otherwise it would not read the value of the variable topic but simply print the string "topic".
Single quotes vs double quotes usually has to do with whether or not string replacement will happen, but in JS it doesn't matter as far as I know
the difference between the 3 is that the first one is a variable assignment where string replacement can happen. the second one is passing a string as an argument and the third one is passing the variable or constant topic
var topicOne = "Community1";
function write(toOutput) {
document.write(toOutput);
}
write(topicOne);
write("topicOne");
write('topicOne');
so here is what the 3 will output:
Community1
topicOne
topicOne
In PHP however the same code will act differently because the double quote implies string replacement
<?php
$topicOne = "community1";
$topicTwo = "community2$topicOne";
function write($toOutput) {
print $toOutput;
}
write($topicOne);
write("$topicOne");
write('$topicOne');
write($topicTwo);
write("$topicTwo");
write('$topicTwo');
?>
will produce a different output
community1
community1
$topicOne
community2community1
community2community1
$topicTwo
see where the difference is?

how to escape single quote in dynamically created HTML tag content

In my javascript code,
I have a variable which have a string. String contains ' or quote in it. Example
var name= "hi's";
I am creating a link dynamically in a code. where it is written as a string i.e a variable content will be used dynamically to create a link on html page.
content= '<a onclick="javascript:fun(\'' + name + '\');">'
Here it is giving problem that quote in variable name completes the string in content. and hence rest portion of content is not recognised..
similar problem arises if var name = 'hi"s';
i.e. if double quote is present in it.
plz help
This is how you would create an anchor properly and completely avoid the need to escape anything.
var name = "Hi's",
anchor = document.createElement('a');
// should have an href
// links will be displayed differently by some browsers without it
anchor.href = '#';
// using onclick for pragmatic reasons
anchor.onclick = function() {
fun(name);
return false;
}
anchor.innerHTML = 'hello world';
// later
mydiv.appendChild(anchor);
Btw, the onclick attribute shouldn't start with "javascript:" at all; that's already implied.
Update
If you're still interested in the inline version, variables need two steps of encoding:
The first is to serialize the variable properly; I would use JSON.stringify() for that
The second is HTML escaping; the simplest form is simply to replace double quotes with their proper encoded values.
For example:
var content = '<a href="#" onclick="fun(' +
JSON.serialize(name).replace(/"/g, '"') + ');">hello</a>';

Create Regex from a string variable in javascript

var tags=["div","span","body"];
for (i=0; i<=tags.length; i++){
source = source.replace(/\&lt\;<tags[i]/i, '<span class="tags[i]"><tags[i]</span>');
}
Basically, I'm trying to put all the opening div,span and body tags around a span with a class set accordingly. But, I am having issues getting the variables inside there.
I can put lines and lines for each different tag but considering this function is called on every key press I want to keep the code as small and efficient as possible.
Or are there other alternatives? I mean it would be even better if something along these lines was possible:
source = source.replace(/\&lt\;<div|<span/i, '<span class="div|span"><div|span</span>');
But, it clearly does not get me anywhere.
You can construct your regex from a string using the RegExp object:
source = source.replace(new RegExp("\\&lt\\;<" + tags[i], "i"), '<span class="' + tags[i] + '"><' + tags[i] + '</span>');
But your idea for an alternative is also possible by capturing the tag and referencing it in the replacement:
source = source.replace(/\&lt\;<(div|span|body)/i, '<span class="$1"><$1</span>');
You can use regexes with | (equivalent of OR): () are used to get the matched elements (div, span or body), and you can get them with $1
source.replace(/<(div|span|body)/i,'<span class="$1"><$1></span>')

Trying to covert a variable into its value within a URL

I'm trying to insert a variable's value into a url, but it's not working; I'm just getting the variable not the value
'myid' and 'verif' are the variables and their values are integers.
This code inserts the url into a hidden field in a form
$('#return').val(http://pegdown.com/index.php?option=com_joom_creditspack&controller=paypal&view=paypal&layout=return&task=checkout&myid=myid&packid=1&verif=verif&jcode=xxx111xxx);
How do I write the following url so the variables 'myid' and 'verif' are converted to their values?
Well you are missing quotes so your code would not work at all.
$('#return').val("http://pegdown.com/index.php?option=com_joom_creditspack&controller=paypal&view=paypal&layout=return&task=checkout&myid=" + myid + "&packid=1&verif=" + verif + "&jcode=xxx111xxx");
You should probably use encodeURIComponent()
You need to quotes " " the strings and concat the variables +
Try
$('#return').val("http://pegdown.com/index.php?option=com_joom_creditspack&controller=paypal&view=paypal&layout=return&task=checkout&myid="+myid+"&packid=1&verif="+verif+"&jcode=xxx111xxx");
JavaScript does not support string interpolation. Try something like this.
myIdVal = encodeURIComponent(myId);
verifVal = encodeURIComponent(verif);
var url = "http://pegdown.com/index.php?option=com_joom_creditspack&controller=paypal&view=paypal&layout=return&task=checkout&myid=" + myidVal + "&packid=1&verif=" + verifVal + "&jcode=xxx111xxx";
$('#return').val(url);
A simple string works for me:
given index = 2,
`a.setAttribute("href", "myDirectory/" + index + ".jpg");` links the anchor to
"myDirectory/2.jpg", ie. the file number is taken from variable index.
Not sure if the setAttribute tolerates multiple tokens in its second parameter, but generally, this works.

Categories