Storing whole code in a variable -- Javascript - javascript

I want to store javascript code in a javascript variable.
To explain clearly, please consider example:
<html>
<body>
<script type="text/javascript">
<!--
function toggle_visibility(id) {
var e = document.getElementById(id);
if(e.style.display == 'block')
e.style.display = 'none';
else
e.style.display = 'block';
}
//-->
</script>
<a onclick="toggle_visibility('1');toggle_visibility('2');">Click here to toggle visibility of element </a>
<div id="1">This is 1</div>
<div id="2">This is 2</div>
<script type="text/javascript">
//document.getElementById('2').style.display='none';
</script>
</body>
</html>
Now suppose all this code is in a variable as a string or something. (i want to do this because i am exporting file to another html page where the code should get copied.)
I used all variables such as
using \ before ' and so on. referring to http://www.w3schools.com/js/js_special_characters.asp

Store like this: var myFunc = function(){ do stuff }
Run like this: myFunc();

To interpret JS code you need to use the JS function eval()
var code = "alert('Ok')";
eval(code);
Here is why using eval() is a bad idea:
Why is using the JavaScript eval function a bad idea?

Maybe try something like this:
var quoteElement = document.getElementById('2');
var quote = quoteElement.value;
// or even ..
var quote = document.getElementById('2').value;
You would now have the text value of your element in a variable.

Related

how to echo javascript generated value in href?

This is my javascript code below (Just to get current url)
<html>
<head>
</head>
<body onload="myFunction();">
<p id="myurl"></p>
<script>
function myFunction() {
document.getElementById("myurl").innerHTML =
window.location.host;
}
</script>
</body>
</html>
And Now i want to use <p id="myurl"></p> as below:
</p>">Share on Facebook <br>
But as it cant be execured inside href="value"
Is there any way to do that with php or something else?
Use this :-
Share on Facebook <br>
With pure javascript (default url in href):
<a id="share_url" href="https://www.facebook.com/sharer/sharer.php?u=">Share on Facebook</a>
<script>
function myFunction() {
var el = document.getElementById("share_url");
el.href += window.location.host;
}
</script>
Demo: http://jsfiddle.net/Lrkjr23o/1/
Other way to create href attribute dynamically:
<a id="share_url">Share on Facebook</a>
<script>
function myFunction() {
var el = document.getElementById("share_url");
el.href = 'https://www.facebook.com/sharer/sharer.php?u=';
el.href += window.location.host;
}
</script>
Demo: http://jsfiddle.net/Lrkjr23o/
I'm assuming client only solution is needed here, server can be anything (PHP, ASP, etc.)
All you've to do is to modify the href property of anchor tag. You can modify your code as -
var elm = document.getElementById("demo");
var URLBase = elm.getAttribute("href");
var fullURL = URLBase.window.location.host;
elm.setAttribute("href", fullURL);

Toggle text with JavaScript

I am learning JavaScript.
I am trying toggle the text on a page using the replaceChild() method. I came up with the code below. I don't understand why it will not work. Pls help.
<html>
<head>
<script>
function toggleText() {
var be= document.getElementById("main");
var b4= be.getElementsByTagName("h1");
var l8 = document.createElement("h1").innerHTML="After";
var l88 = document.createElement("h1").innerHTML="Before";
if (b4[0].innerHTML=="Before"){
be.replaceChild(l8,b4[0])
}
if (b4[0].innerHTML=="After") {
be.replaceChild(l88,b4[0]);
}
}
</script>
</head>
<body>
<div id="main" onclick="toggleText()">
<h1>Before</h1>
</div>
</body>
</html>
As CBrone wrote, you have to create h1 instance first, store it to variable and then call innerHML on the variable.
Another problem is if structure. First you replace the element and then test the same element for another condition and do another operation. In this case is better to use if ... else if ... statement instead of if ... if ..., which is the root of your problem.
Here is working toggleText function
function toggleText() {
var be= document.getElementById("main");
var b4= be.getElementsByTagName("h1");
var l8 = document.createElement("h1");
l8.innerHTML="After";
var l88 = document.createElement("h1");
l88.innerHTML="Before";
if (b4[0].innerHTML == "Before")
{
be.replaceChild(l8, b4[0]);
}
else if (b4[0].innerHTML=="After")
{
be.replaceChild(l88, b4[0]);
}
}
Here is working fiddle
In addition to what’s been said in comments already:
var l8 = document.createElement("h1").innerHTML="After";
var l88 = document.createElement("h1").innerHTML="Before";
After this your variables do not contain references to the created elements, but the string values that you assigned to their innterHTML. (The result of an assignment operation is the assigned value.) And trying to pass text values instead of element references to replaceChild afterwards must fail for that reason.
Do this in two steps – create the elements first and save their reference into the variables – and then manipulate their innerHTML afterwards.
var l8 = document.createElement("h1");
l8.innerHTML="After";
var l88 = document.createElement("h1");
var l88 = .innerHTML="Before";
(And maybe use better suited variable names, because if you keep your current “naming scene” up you’ll get confused sooner or later.)
May I suggest the following, for better readability:
<html>
<head>
<script>
function toggleText() {
var be= document.getElementById("main");
var b4= be.getElementsByTagName("h1")[0];
if (b4.innerHTML=="Before") {
b4.innerHTML = "After";
}
else if (b4.innerHTML=="After") {
b4.innerHTML = "Before";
}
}
</script>
</head>
<body>
<div id="main" onclick="toggleText()">
<h1>Before</h1>
</div>
</body>
</html>

How to access smarty variable and assign to jquery variable?

I just need your help about my code. My problem is how can I access smarty variable within jquery or javascript file? Becuase my smarty variable is a URL request from my controller. And I need to use that variable for creating validation. Here's my code.
{$get.search_by} {**works without error**}
{literal}
<script type="text/javascript">
$(document).ready(function(){
var dispatch = "{$get.search_by}"; //can't access
var new_class = "it3 ir3 il3 jt10 jr05 jl05 kt03 kr04 kl04";
var old_class = "it3 ib3 il3 jt05 jb05 jl10 kt04 kb04 kl03";
var toggleState = true;
//could not access
if(dispatch == companies.catalog){
alert("catalog");
}else{
alert("product search");
}
console.log(dispatch);
Try this code
var dispatch = '{/literal}{$get.search_by}{literal}'
To make things cleaner, you can move the {literal} tag down and also escape the $get.search_by variable (in case search_by may have a string with a quote i.e. "let's try"):
<script type="text/javascript">
var dispatch = '{$get.search_by|escape:'javascript'}';
{literal}

Replacing function contents dynamically in JavaScript

How do you completely replace a function in JavaScript?
I got this code, but it doesn't work. The DOM gets updated, though. What's up with that?
<html>
<head>
<script id="myScript" type="text/javascript">
function someFunction() {
alert("Same old.");
}
</script>
</head>
<body>
<input type="button" onclick="someFunction();" value="A button." />
<script>
function replace() {
var oldFunctionString = someFunction.toString();
var oldContents = oldFunctionString.substring(oldFunctionString.indexOf("{") + 1, oldFunctionString.lastIndexOf("}") );
var newCode = "alert(New code!);";
var newFunctionString = "function someFunction(){"+newCode+"}";
var scriptTag = document.getElementById('myScript');
scriptTag.innerHTML = scriptTag.innerHTML.replace(oldFunctionString,newFunctionString);
}
replace();
</script>
</body>
</html>
JSfiddle here
Setting .innerHTML doesn't re-execute a script. If you really wanted to do that, you'd have to create a new script element and append it to the DOM, which then overwrites what the previous script has done (not possible in all cases, of course).
If you want to replace that function, just use
somefunction = function() {
alert(New code!); // syntax error, btw
};
Of course, to replace only parts of the code (not knowing all of it) you could try regex and co. Still just reassign the new function to the variable:
somefunction = eval("("
+ somefunction.toString().replace(/(alert\().*?(\);)/, "$1New code!$2")
+ ")");
It seems you are trying to work with strings, not the function itself. Just do this instead:
someFunction = function () { /* your function code here */ }

Change visibility of a control in JSP based on bool value

I'm guessing I will need to use javascript to do this, but I'm completely clueless. I've never used javascript before. Can someone give me a quick sample of how to change the visibility of a button based on a bool value in a JSP page?
If you are thinking about using it only once it's easy to include JSP value in your JS code:
<script type="text/javascript">
var e = document.getElementById("foo");
var myvar='<%=myScriptletVar %>'
if (myvar)
e.style.display = 'none';
</script>
Here was my final solution:
<c:if test="${viewModel.facebookToken != ''}">
<script type="text/javascript">
var e = document.getElementById("facebookButton");
e.style.display = 'none';
</script>
</c:if>

Categories

Resources