javascript code remove itself after being run - javascript

I am looking for a way to fill an array table by javascript code then remove that code not to allow users copy the table directly(or at least make it hard) from page as HTML.
<script>
....
</script>
how to remove the java script from the page after completing its mission?
thanks

I don't really see a point in removing the JavaScript, but it would be possible. Give the script-element an ID to make it easier to select. Then place the code that will handle the removal in a separate script-element.
Given that the code you wan't to remove isn't asynchronous, something like this would do it:
<script id="foo">
// Do your stuff here, create the table or whatever necessary
</script>
<script>
(function () {
var node = document.getElementById("foo");
if (node.parentNode) {
node.parentNode.removeChild(node);
}
})();
</script>
Demo
Update:
As Juhana points out in the comments, this will remove the script-element from the DOM, but the script element will still be visible if you look at the actual source of the page.

You can remove script element or do anything else but user can still get the table through debug mode. There are some ways to encrypt your source code,try: http://jsobfuscate.com/

May be you can make it hard by disabling copy and paste function in your webpage:
<script type="text/JavaScript">
function killCopy(e){
return false
}
function reEnable(){
return true
}
document.onselectstart=new Function ("return false")
if (window.sidebar){
document.onmousedown=killCopy
document.onclick=reEnable
}
</script>
see http://www.boogiejack.com/no_copy_paste.html
But still users can get it, because they already have a copy of html on their local machine

document.currentScript.remove()

Related

JS class change script? (Working in JS Fiddle)

JS noob here looking for some help. I've written something extremely basic in able to change a class which would hide a page element. The hide class just has a display none.
I've got it working fine in JS fiddle but when replicating it on my site, nothing happens? What am I doing wrong?
JS Fiddle - https://jsfiddle.net/MattPremier/x8rmn4cb/2/
<script type="text/javascript">
window.onload = function () {
var bookShow = "No";
if (bookShow == "No") {
// execute this code
document.getElementById('booking-show').classList.add('hide-widget');
}
else {
// execute this code
document.getElementById('booking-show').classList.add('show-widget');
}
};
</script>
<div id="booking-show" class="show-widget"><p>WORKING?</p></div>
I would recommend checking your CSS to make sure that the display isn’t otherwise set unless you need it to be set then inside the hide-widget CSS class put:
“display: none !important;”
And also remove show-widget from the object at the bottom as it might be conflicting with CSS.
Note Sorry for the bad formatting of this message as I’m on my cell phone.

How to guarantee that a script in the middle of the body runs after all the DOM has finished load

In my <body> I have a component that inserts a script that is supposed to run only after all the page has completely loaded:
<script>
$('<script id="smallPlacarScriptdId">\
$(window).load(function() {\
$(".main.right").hide();\
$("#rightzero").show();\
$(".comp.smallPlacard.firstChild").click(function () {\
var clicked = $(this).parent().attr("id");\
$("main.right").hide();\
$("#right"+clicked+"").show();\
});\
})\
<\script>').appendTo("body")
</script>
That's not happening and this script (1) is correctly inserted into the DOM but (2) is not working (not hiding .main.right nor showing #rightzero).
I though that by using this approach I would guarantee that it would be the same as just put this script at the bottom of the <body> but it isn't. In fact if I put it (not dynamically like this) in my page it produces the desired result.
I tried setTimeout() to validate my theory but I'm getting an error in jQuery and I'm lost.
That might be the problem:
<\script>').appendTo("body")
Browser might think you are actually closing your script tag. Change it to
</' + 'script>').appendTo("body")
Check this plunker out: http://plnkr.co/edit/Oc6yrFMdPoW2WV257CBQ?p=preview
Just use this code
<script id="smallPlacarScriptdId">
$(window).load(function() {
$("main.right").hide();
$("#rightzero").show();
$(".comp.smallPlacard.firstChild").click(function () {
var clicked = $(this).parent().attr("id");
$("main.right").hide();
$("#right"+clicked+"").show();
});
})
</script>
Sorry I didn't read you question well enough.
Javascript will allow you to access undeclared variables, so use that to your advantage. Check if a variable is set, undefined is treated as a false so no need for initialization. As soon as you enter the code just set it to true so nothing else will execute.
Hopefully this solves the problem for you, but you really should look at from the server avoiding the javascript, it will bloat the page.
<script>
if (!myScriptHasLoaded)
{
myScriptHasLoaded = true;
$(window).load(function() {
$("main.right").hide();
$("#rightzero").show();
$(".comp.smallPlacard.firstChild").click(function () {
var clicked = $(this).parent().attr("id");
$("main.right").hide();
$("#right"+clicked+"").show();
});
});
}
</script>

Can I shorten this script? (update DB table and refresh)

I really want to know if there is a shorter alternative to writing this code. I have attempted to shorten it to 2 or 1 functions and achieved miserable failure. I'm seeking constructive feedback!
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript">
function f_solar_1() {
$.get("f_solar_1.php");
return false;
}
</script>
<script type="text/javascript">
function refresh(){
location.reload(true);}
</script>
<script type="text/javascript">
function both(){
f_solar_1()
setTimeout(refresh, 5);
}
</script>
Activate
Details:
This code is an excerpt from my php page that displays a table from my mysql database (I'm using wamp).
The "Activate" text at the bottom is supposed to UPDATE a variable on that table, and does so via the f_solar_1.php file.
The issue is the table reflecting the database does not automatically reflect this change.
So I made a "reload()" function to refresh the page, and the "both()" function to time the refresh after updating the database.
I have known basic html for a while, but I am new to mysql, ajax, and php as of this morning, and this is my attempt to dive into it.
My code works fine, it just bothers me not knowing if I can accomplish the same thing within one function.
Thank you in advance!
UPDATE: Thankyou to Dat Pham for pointing me in the right direction!
<script type="text/javascript">
function newfunc(){
$.get( "f_solar_1.php", function( data ) {
location.reload(true);
});}
</script>
<span onclick="newfunc();">newfunc</span>
The code is all in one function (well...) and without causing a refresh and php recall timing conflict.
Making 1 function do all the thing is considered bad practice, a function should do and only do an atomic task. Your code is fine except some minor points:
ajax call $.get() and location.reload should not be used with each other as this destroy the meaning of ajax call. You can pass a callback function to handle data from backend server like
$.get( "f_solar_1.php", function( data ) {
alert( "Load was performed." );
});
Combine all your script tags into 1 with all your function declare
Regards,
Have you checked the database through the backend (phpmyadmin for example) and verified if the changes are being made even though it's not displaying?
i'm wondering if your page isn't really refreshing, and simply going to "#". Check the "return false" - it's not really applying to the "A" link, you would have to put "return false" in the 'both' function for that to cancel the link. But you might not want to do it that way after taking a minute to read this: The return false onclick anchor not completely working
additionally, I'd recommend using the jquery add event listener to trigger your function calls, and get the onClick out of your html tag. Bonus if you learn how to do it without jquery. Read this real quick jquery href and onclick separation

Event handlers aren not attaching to select menu

I'm learning javascript and jquery and I'm a bit stuck. For some reason the event handlers are not attaching correctly. I thought the .change() was the correct one to use for select menus.
$('#tier1').change(function(){
var tier1 = $('#tier1').find(":selected").text();
if(tier1 != 'Month'){
$('#tier2').removeAttr("disabled");
}
});
You need to take of below things.
Make Sure jQuery library is added into head tag,
make sure you are wrapping your code into $(document).ready(function() { //code });
Make Sure ID for each DOM are unique.
Make Sure DOM is present which you are selecting using jQuery selector,
Example
<head>
<script src="jQuery.js"></script>
<Script>
$(document).ready(function(){
$('#tier1').change(function(){
var tier1 = $('#tier1').find(":selected").text();
if(tier1 != 'Month'){
$('#tier2').removeAttr("disabled");
}
});
});
</script>
</head>
<input id="tier1" />
For what I know, .change() is to be used with select menus... but I think there's something else amiss with your code.
Instead of
var tier1 = $('#tier1').find(":selected").text();
try
var tier1 = $('#tier1').find(":selected").val();
If not, scatter some console.log around... Firefox's Firebugger and Chrome's Dev Tools should catch them and give you some clues as to what is happening.

Cannot load HTML in a div that was ajax'd in

Good afternoon, I am at a total loss on why this is happening. I have searched online and tried to understand what I'm doing wrong for 5+ hours and could find no solution. Here is the situation.
I have 3 pages (index.html, index.js, and stuff.html)
index.html is the main page and uses jQuery to load an HTML page into a div.
<html>
<head>
<script type="text/javascript" src="index.js"></script>
</head>
<body>
<div id="stuffHolder"></div>
<script type="text.javascript">
$(document).ready(function(){
$('#stuffHolder').load('stuff.html');
});
</script>
</body>
</html>
The stuff.html page loads just fine for me.
Inside the stuff.html I have 2 div's
1. One of the DIV's uses sprites as anchor tags to call a function named actOnStuff(options).
<div id="myStuff"><a class="myStuffSprite" href="Javascript:actOnStuff('newStuff')"><span>New Stuff</span></a></div>
<div id="yourStuff"><a class="yourStuffSprite" href="Javascript:actOnStuff('oldStuff')"><span>Old Stuff</span></a></div>
The other DIV is empty but will have innerHTML written to it later.
Inside index.js, which sits on the index.html page, I have a function
function actOnStuff(youSelected){
strHTML = "";
switch(youSelected){
case "newStuff":
strHTML += "<div id='newDIV'><span>You selected New</span></div>";
break;
case "oldStuff":
strHTML += "<div id='oldDIV'><span>You selected Old</span></div>";
break;
}
$('#placement').html(strHTML);
alert($('#placement').html());
}
My problem is that when I alert the innerHTML of the placement DIV it shows that the necessary DIV from the function as added in the alert. HOWEVER, nothing shows up in the placement DIV at all.
Any help you can provide would be wonderful as I am at a total loss as to what the problem is. Thanks in advance.
I'm not sure I can help solve the actual problem, but there's many issues and bad practices in your code that I'd like to point out for the greater good of the community.
Here's my take on your code:
HTML in body
<div id="stuff-holder"></div>
HTML in stuff.html
<div id="my-stuff">
<a class="my-stuff-sprite" href="#"><span>New Stuff</span></a>
</div>
<div id="your-stuff">
<a class="your-stuff-sprite" href="#"><span>Old Stuff</span></a>
</div>
Bad practice: CSS and HTML is most of the time not case-sensitive, so when naming IDs with camelcase such as fooBar, could create confusion with foobar or Foobar. Instead, use lowercase only and dash as separator (like in CSS).
JavaScript in index.js
I moved your ready function into index.js. I don't see a reason why you would want that in your HTML document when you already have a separate JavaScript file.
// Shorthand for ready
$(function(){
// Cache the selector
var $placement = $("#placement");
// Put function in the local scope so we don't clutter the global scope
function actOnStuff(youSelected) {
// Not declaring variables with var, makes it global (bad idea!)
var html = "";
switch (youSelected) {
case "my-stuff":
html += '<div id="new-div"><span>You selected New</span></div>';
break;
case "your-stuff":
html += '<div id="old-div"><span>You selected Old</span></div>';
break;
}
// Put new html in placement element
$placement.html(html);
// Use console.log to debug your code instead of alert
console.log($placement.html());
}
// Load stuff into stuff holder and bind event handler to load event
$("#stuff-holder")
.load("stuff.html")
.on("load", function() {
// After it has loaded, bind click events
$("#my-stuff .my-stuff-sprite, #your-stuff .your-stuff-sprite").click(function(e) {
// Prevent default click behavior
e.preventDefault();
// Get id of parent
var id = $(this).parent()[0].id;
// Execute function
actOnStuff(id);
});
});
});
Bad practice: Executing JavaScript within the href is a big no-no in todays environments. Even using onclick attributes et al is since long outdated.
Tip: Passing a function directly into jQuery is a shorthand for $(document).ready
Tip: Use console.log() instead of alert() to output everything from objects to strings to your log (might give you errors in older IE)
I still don't know where your placement element is located. Perhaps that's your culprit? If you have any questions about the above or anything else, don't hesitate to ask.
Also, check out jQuery Fundamentals which is a great resource for everyone using jQuery, from beginners to pros.
Edit: Check this jsFiddle for a demonstration of the above.
before
<script type="text/javascript" src="index.js"></script>
you should load jquery library first
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="index.js"></script>
Make sure you only have ONE element with id="placement", IE will fail if you have more than one.
Also what is the output of alert(strHTML); putted just before $('#placement').html(strHTML); does it output the string right?

Categories

Resources