string inside php inside html inside javascript - javascript

i've searched on the site but i could find nothing that could help me.
I have a javascript code inside html inside php, i would like to know how i can put a string inside the javascript code with "breaking" the href with double quotes. Here is the code i have:
return '<li class="slide_li" onmouseover="gmarkers['+marker_num+'].setIcon(getMarkerImage("grey", price, cur));" onmouseout="gmarkers['+marker_num+'].setIcon(gicons.blue)">'+details+'</li>';
The "grey" value breaks the href, i tried different ways like:
'grey', \'grey\', \"grey\" ecc.. but none of this worked for me. Any help is really appreciated. Thanx!

To avoid such pain in the future, I am suggesting you my way of doing things in such scenarios.
Since you are already using jQuery library, why not to use its way of handling events:
$('li.slide_li').on({
mouseover: function(e){
},
mouseoutleave:function(e){
});
instead of using inline javascript. This will make you away from dealing with quotes. Additionnaly, by seperating the concerns this way, you make your php return only markup.
About additional variables (like the variable containing 'grey'), I suggest you use data attributes, something like:
return '<li class="slide_li" data-color='grey'></li>
in javascript:
var color= $('li.slide_li').data(color);
// use color variable in code inside mouseover and mouseout
I am not telling here that the other answers are not adressing your current problem, I am only sharing a way I was told in the past it is a better way.

You need to wrap your javascript variable with additional single quote and then you need to used backslash like below:
return '<li class="slide_li" onmouseover="gmarkers[\''+marker_num+'\'].setIcon(getMarkerImage("grey", price, cur));" onmouseout="gmarkers[\''+marker_num+'\'].setIcon(gicons.blue)">'+details+'</li>';

I tried with this "grey"
and it works!
Thank you everybody!

Try setting the variable outside of the javascript first:
var variable="grey"
return '<li class="slide_li" onmouseover="gmarkers['+marker_num+']
.setIcon(getMarkerImage(variable, price, cur));" onmouseout="gmarkers['+marker_num+']
.setIcon(gicons.blue)">'+details+'</li>'
;

Related

How to store a template in an expression in Handlebars.js?

I want to place my templates on several places in the DOM without having to write the jQuery expression over and over again. I want to place my template in the DOM by just typing the variable/attribute {{template}} anywhere in the body.
Is this doable using Handlebars? If not, is there any other way for me to achieve this?
You need to use HandleBar helpers
handlebar_helpers
p.s. dont forget to use safestring else it will be escaped by default
Updating with answer based on ur comment
The link i provided did give out an excellent explanation. However please find below an example.
Assume your need to return a welcome message when a name is given
Handlebars.registerHelper('welcome', function(name) {
return new Handlebars.SafeString(
"<p>Hi "+name+", welcome to stackoverflow</p>"
);
});
Then calling
{{{welcome "sagittarius"}}} will return
Hi sagittarius, welcome to stackoverflow

JavaScript Error, Missing Name After . Operator

I am trying to get the innerHTML of a hidden span. The JavaScript is from an iframe HTML page, and the hidden span resides in the parent page. A different function works when accessing contents of a list from the parent, but I can't seem to get at my span...
WORKS
document.getElementById(parent.genL[i]);
DOESNT WORK
document.getElementById(parent."span"+i).innerHTML;
- SyntaxError: missing name after . operator
The above line of code resides in a for loop and as it iterates through i it will grab data from each separate span. the hidden spans start at ID "span1" through upwards of 10-40k different hidden spans.
Anyways, I have a feeling that it has to do something with trying to concatenate the string int i. I assume i is an int anyways. Any thoughts? Thanks so much everyone!
Edit - Words, and added the innerHTML portion to the doesn't work line of code. Not sure if that will be making a difference or not...
Edit2 - Great answers everyone, learned some good syntactical tricks :) I simply moved the parent. portion to the front of the code as reccomend by the comment of mplungjan and the answer from Jacob T. Nielson. For some reason I still got the error using the brackets as suggested, but I will definitely tuck the brackets into my memory for future similar situations!
parent.document.getElementById("span"+i).innerHTML;
:)
Try changing it to an indexer.
document.getElementById(parent["span"+i]);
If the parent in the brackets is an object and you're trying to access something like parent.span1 then you need to use bracket notation instead of the dot.
document.getElementById(parent["span"+i]); should work fine.
I think what you are trying to do is get the i-th span element on the parent page. Correct?
You can do it like this
var s = parent.document.getElementsByTagName('span')[i];
s.innerHTML // <-- access innerHTML

Converting plain JavaScript to jQuery

really simple question, just having a hard time actually making it work. I have a snipet of code that's javascript that I'm trying to write in jquery and can't quite get it.
effects_of_yoga_2010_INFO.style.setProperty('-webkit-transform',
'rotateZ('+effects_of_yoga_2010_DEG+'deg)');
and I had tried it as
$("#effects_of_yoga_2010_INFO").css("-webkit-transform",
"rotateZ('+effects_of_yoga_2010_DEG+'deg)");
but the jquery snippet doesn't work, I'd really appreciate any help I can get on this, I'm sure it'll be breeze for someone.
It should be:
$("#effects_of_yoga_2010_INFO").css("-webkit-transform",
"rotateZ("+effects_of_yoga_2010_DEG+"deg)");
you were mixing single quotes with double quotes.
Assuming effects_of_yoga_2010_DEG is another id of an element with a value, try:
$("#effects_of_yoga_2010_INFO").css("-webkit-transform",
"rotateZ('" + $("#effects_of_yoga_2010_DEG").val() +"'deg)");
$("#effects_of_yoga_2010_INFO").css("-webkit-transform", "rotateZ('+effects_of_yoga_2010_DEG+'deg)");
That doesn't look right. Unless this was a copy-paste error you should split the variable values from the rest of the strings the same way as the JavaScript version had done.
$("#effects_of_yoga_2010_INFO").css("-webkit-transform", "rotateZ(" + effects_of_yoga_2010_DEG + "deg)");
Of course, this is based on not knowing what effects_of_yoga_2010_DEG is. I'm assuming it simply contains the value you are looking for and can be used the same as the JavaScript version had done.

Error in javascript function

I am using the following code
function xhi(aax)
{
var aby=document.getElementById(aax);
aby.style.bottom=(parseInt(aby.style.bottom)+(screen.height-42)/10)+'px';
if(parseInt(aby.style.bottom)<(screen.height-42))setTimeout('xhi("'+aax+'")',25);
}
When i run this code the function calls itself only two times . second time aby.style.bottom becomes Null.Why?
Check the bottom value. It might be crazy, but if the value is something like 008, 010, etc.
parseInt treats the number as octal. In order to avoid this, use :
parseInt(aby.style.bottom,10)
Why are you using bottom? I believe the best approach is the top attribute.
If everything else fails, jQuery has some nice functions to animate and to grab those style attributes.
I am not sure but try after removing from your code +'px' .

Escaping dilemma in Javascript

I have the following
var id='123';
newDiv.innerHTML = "";
Which renders in my HTML.
The problem I have is that I wish to take the call to the method TestFunction, and use as a string parameter in my function StepTwo(string, boolean), which would ideally end up in live HTML as shown...
notice how the TestFunction is a string here (it is executed within StepTwo using eval).
I have tried to format my JS as by :
newDiv.innerHTML = "";
but while this appears to me correct in my IDE, in the rendered HTML, it as garbelled beyond belief.
Would appreciate if anyone could point me in the right direction. Thanks!
One of the biggest capital failures on the internet is creating html in javascript by gluing strings together.
var mya = document.createElement("a");
mya.href="#";
mya.onclick = function(){
StepTwo(function(){
TestFunction('123', false );
}, true );
};
newDiv.innerHTML = "";
newDiv.appendChild(mya);
This Eliminates the need for any fancy escaping stuff.
( I probably should do 'onclick' differently, but this should work, I'm trying hard not to just use jQuery code to do everything )
Heres how I would do it in jQuery:
jQuery(function($){
var container = $("#container");
var link = document.createElement("a"); /* faster than $("<a></a>"); */
$(link).attr("href", "Something ( or # )" );
$(link).click( function(){
var doStepTwo = function()
{
TestFunction('123', true );
};
StepTwo( doStepTwo, false ); /* StepTwo -> doStepTwo -> TestFunction() */
});
container.append(link);
});
There is no good excuse for gluing strings together in Javascript
All it does is ADD overhead of html parsing back into dom structures, and ADD potential for XSS based broken HTML. Even beloved google get this wrong in some of their advertising scripts and have caused epic failures in many cases I have seen ( and they don't want to know about it )
I don't understand Javascript is the only excuse, and it's NOT a good one.
Try using " instead of \"
newDiv.innerHTML = "<a href="#"...
You should be using " not " or \" inside an HTML string quoted with double-quotes.
NewDiv.innerHTML = "";
There's probably a better way to do this - any time you find yourself using eval() you should stand back and look for a different solution.
You claim that eval is the right thing to do here. I'm not so sure.
Have you considered this approach:
and in your StepTwo function
function StepTwo(func,args,flag){
//do what ever you do with the flag
//instead of eval use the function.apply to call the function.
func.apply(args);
}
You could create the a element and attach to the click event using DOM Methods.
A Javascript Framework (like the ubiquitous jQuery) would make this a lot easier.
Your biggest problem is using eval, it leads to so many potential problems that it's nearly always better to find an alternative solution.
Your immediate problem is that what you really have is
as the next " after the start of the onclick attribute, closes it. Use " as others have suggested. And don't use eval.
You need to alternate your " and '.
Maybe you don't need quotes around the 123, because of Javascripts flexible typing. Pass it without quotes but treat it as a string within TestFunction.
Hey guys, thanks for all the answers. I find that the quot; seems to work best.
I'll give you guys some votes up once I get more reputation!
In regards to eval(), what you see in the question is a very small snapshot of the application being developed. I understand the woes of eval, however, this is one of those one in a million situations where it's the correct choice for the situation at hand.
It would be understood better if you could see what these functions do (have given them very generic names for stackoverflow).
Thanks again!
The best way is to create the element with document.createElement, but if you're not willing to, I guess you could do or use ".
In your code:
newDiv.innerHTML = "";
If it doesn't work, try changing "\'" to "\\'".
Remember that the " character is used to open and close the attribute on HTML tags. If you use it in the attribute's value, the browser will understand it as the close char.
Example:
<input type="text" value="foo"bar"> will end up being <input type="text" value="foo">.
...
I know this is hella' old now, but if anyone has issues with escaped strings when using eval (and you absolutely have to use eval), I've got a way to avoid problems.
var html = '';
eval('(function(div, html){div.innerHTML = html;})')(newDiv, html);
So, what's going on here?
eval creates a function that contains two parameters, div and html and returns it.
The function is immediately run with the parameters to the right of the eval function. This is basically like an IIFE.
In this case
var myNewMethod = eval('(function(div, html){div.innerHTML = html;})');
is basically the same as:
var myNewMethod = function(div, html){div.innerHTML = html;}
and then we're just doing this:
myNewMethod(newDiv, html); //where html had the string containing markup
I would suggest not using eval. If it can't be avoided, or if you control all the inputs and there's no risk of injection then this will help in cases where string escapes are an issue.
I also tend to use Function, but it isn't any more secure.
Here's the snippet I use:
var feval = function(code) {
return (new Function(code))();
}

Categories