Simple JavaScript question - where does this go - javascript

I'm trying to follow the tutorial to use jQuery UI plugin. I'm new to JavaScript and I'm not sure where to put a particular bit of code.
I've got everything I need downloaded. I've put the files where they need to be and included them in the like I'm supposed to - all no problems there. But next I get a little stuck due to my utter noobieness.
It says I give an ID to the element I want to use e.g. id="date" and call:
$('#date').datepicker();
on it.
Where do I put the above code? Along with the html and php? Or in the Javascript file I've included?

First load your jQuery library:
<script src="/jquery/1.6.3/jquery.min.js" type="text/javascript"></script>
Then load your jQuery UI library:
<script src="/jqueryui/1.8.16/jquery-ui.min.js" type="text/javascript"></script>
Then, load your code with something like:
<script type="text/javascript">
$(document).ready(function() {
$('#date').datepicker();
});
</script>

Put it within a script tag like :
<script type="text/javascript">
$(function(){
$('#date').datepicker();
})
</script>

You will usually execute jQuery-code on $(document).ready(), but there are cases where you don't. Maybe this gets you started: http://docs.jquery.com/How_jQuery_Works

In your HTML/PHP code between script tags. Mostly in the head section or at the bottom just infront of the end body tag.
your code would look like this: ...
<script type="text/javascript">
$(document).ready(function() {
$('#date').datepicker();
});
</script>

the code you are trying to use is Javascript, so it normally goes into a .js file, or into a script type="javascript" tag of your resulting html. As it uses the jQuery $ function, you need to have the jQuery Library included before calling the code you have in your question. The code itself is best placed into the document.ready function that jQuery provides, so it will be called only when all the neccessary libraries are loaded and the html Dom tree has been constructed.
$(document).ready(function() {
$('#date').datepicker();
});

You have to put that code inside the javascript file such that the input text box element is already append to DOM.For example,
var input = document.createElement('input');
input.type = 'text';
input.id = 'date';
document.body.appendChild(input);(or)[If div to append then div.appendChild(input);
$('#date').datepicker();
Here,the input element is appended to body or the parent div.Then the datepicker() can be rendered

Related

Disable script tag in html file or change script tag type/src using javascript

I want to disable the script tag or if its possible to change script src or type in this script using javascript?
<script type="text/javascript" src="./1.js.download"></script>
I can't add id in this code.
please help and feel free to ask anything if you don't understand
How about removing it altogether? The example is a simple function that get an element by the given selector and remove it. FYI if you don't want the <script> to actually load, then your'e out of luck. It'll be parsed as long as it's in the HTML, there's no way to avoid it from loading by JavaScript.
In the example there are 3 <script> tags and the target is in the middle. document.querySelector("script") will stop at the first match so you'll need a more specific selector. To target the second tag I used script:nth-of-type(2). You can verify success using by F12
const killTag = selector => document.querySelector(selector).remove();
killTag(`script:nth-of-type(2)`);
<script src="https://cdn.jsdelivr.net/npm/jquery/dist/jquery.min.js"></script>
<script type="text/javascript" src="./1.js.download"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/js/bootstrap.bundle.min.js"></script>
You can remove src from script tag like this:
s = document.querySelectorAll('script')
console.log(s[1])
s[1].setAttribute('src', '')
console.log(s[1])
<script type="text/javascript" src="./1.js.download"></script>
You will have maybe multiple scripts in your dom. then you have take a look which element it is and change the key from the collection. in this case the key was 1.
If you need to select specific script element you can get it by attribute like this:
let ok = document.querySelector('[src="./1.js.download"]');
//Then you can either change id or type:
ok.setAttribute('id', 'ok');
ok.setAttribute('type', 'module');

Can't append script element to head

Current variant looks like that (I tried solution offered here: Can't append <script> element):
var s=document.createElement("script");
s.type="text/javascript";
s.src="js/properties.js";
$("head").append(s);
Previous variant was:
$("head").append($('<script type="text/javascript" src="js/properties.js"></script>'));
And both of them don't work. "properties.js" is also in "js" folder, but if I remove this part of path, it doesn't change anything.
I also tried to use ' instead " and check addBlock: I had it installed, but it's disabled on this page.
Changing "append" function to "appendChild" also didn't help.
"properties.js" contains just one line:
var PREFIX_URL = "http://localhost:8080/app-rest-1.0.0-SNAPSHOT";
And firstly I declare it in "main.js" to which I, in fact, try to connect this file.
Explain, please, what I'm doing wrong.
Add all your <script> tags right before the closing </body> tag, because when the browser encounters a <script> tag it begins downloading it and stops rendering of the page. So by placing them at the bottom of the page you make sure your page is fully loaded before trying to interact with the DOM elements. Also $("head") returns an array of all the <head> tags. You should also enclose your calls in a $(document).ready() function.
<!-- Your html tags here -->
<script type="text/javascript">
$(document).ready(function(){
var s=document.createElement("script");
s.type="text/javascript";
s.src="js/properties.js";
$("head")[0].append(s);
});
</script>
</body>
I made JSBin example. You can see in console that last script tag is the one you need. So the your code is correct.
If your IDE don't highlight 'var' - it may be error not in javascript. You can place it in a wrong place for example.
Can you provide link to a gist (or pastie.org or smth) for us to better understand your problem.
P.S. The code $("head")[0].append gives me undefined ( note to previous answer)

Injecting HTML that contains JS

I've been given some great tips on how to inject HTML into HTML that I can't edit.
The trouble is now that the snippet contains JS it won't render to the page.
The Jquery looks lke this:
$(document).ready(function() {
var $body = $(document.body);
if ($body.is(".ly_productdetails.ProductDetails.en.en_GB")) {
$('.info_section').prepend('<div id="test-widget"></div><script type="text/javascript" src="/frontend/latest/build.min.js" data-test="test-widget" data-instance="xyz" data-apikey="12345678" data-tags="" async="async"></script>');
}
});
I tried putting backslashes in before the quotations but this didn't work.
How else can you write this to the page so that the JS is included?
Many thanks,
Adam
JSfiddle : https://jsfiddle.net/fs6qgzrj/
This is a security feature. jQuery allows <script> elements in HTML code but it won't execute them (at least not the src="..." part; inline scripts work). This is because jQuery has no way to make sure the script isn't malicious or from a safe source (an error in your code might allow people to enter scripts in a form element).
Use jQuery.getScript(url, successCallack) instead.
See also: jQuery - script tags in the HTML are parsed out by jQuery and not executed
It looks like jQuery won't load an external script when parsing HTML. But if you create a script element it will:
$('body').prepend($('<script>', {
src: 'http://dev.bridgebase.com/barmar_test/test.js'
}));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

How to initialize javascript on a webpage using the datatables plugin

I am attempting to use a jQuery plugin called DataTables. I am new to jQuery and setting this up on my own site in as basic a way as possible to get familiar with it. On the last step on setting it up the guide says to:
"Initialize DataTables".
"All we need to do now is to tell DataTables to actually work on the page."
The code I am suppose to Initialize is the following:
$(document).ready( function () {
$('#table_id').dataTable();
} );
I assume I am suppose to put it in a script tag in the head or right after the head like so:
<script type='text/javascript'>
$(document).ready( function () {
$('#table_id').dataTable();
} );
</script>
sorry for such a basic question and enlightenment would be great! thanks!
your scripts looks correct
make sure you are inluding jquery and datatable pluging
you can inlude them in the head tag or in the end of the body tag best practice to inlude all your script in the end of your body tag before the </body>
and make sure to follow the right order jquery then datatables then your sctipts
and make sure the table is using thead and tbody
good luck and Merry Xmas

How can I create a javascript badge or widget?

I want to create a javascript badge that displays a list of links. We host the javascript on our domain. Other sites can put an empty div tag on their page and at the bottom a reference to our javascript that would render the content in the div tag. How do you implement something like this?
I would give the SCRIPT tag an ID and replace the script tag itself with the DIV + contents, making it so they only have to include one line of code. Something along the lines of the following:
<script id="my-script" src="http://example.com/my-script.js"></script>
In your script, you can swap out the SCRIPT tag for your DIV in one fell swoop, like so:
var scriptTag, myDiv;
scriptTag = document.getElementById('my-script');
myDiv = document.createElement('DIV');
myDiv.innerHTML = '<p>Wow, cool!</p>';
scriptTag.parentNode.replaceChild(myDiv, scriptTag);
just as you say, have them put a div at the bottom of their page:
<div id="mywidget"></div>
then have them link to your javascript:
<script type="text/javascript" src="http://yourdomain.com/mywidget.js"></script>
then have them alter their body tag, or onload to call your script
<script type="text/javascript">
document.body.onload = loadYourWidget();
</script>
You do not necessary need an initial div to fill with you link list.
Simply create the div using document.write at the place where the script is placed.
<script type="text/javascript" src="http://domain.com/badge.js"></script>
... and in your script:
var links = [
'One',
'Two',
'Three'
];
document.write("<div>" + links.join(", ") + "</div>");
Another benefit is that you do not have to wait for the page to be fully loaded.
Like #Owen said, except why not craft your javascript so that
<script type="text/javascript" src="http://yourdomain.com/mywidget.js"></script>
does the work of populating <div id="mywidget"></div> on its own, thus negating the need for them to call loadYourWidget() from their DOM load if you include the script tag right after the mywidget div in the html source. This isn't really a best practice, but I think it'll work.
Example for your mywidget.js code:
document.getElementById('mywidget').innerHTML = "<a href=''>LinkOne</a> <a href=''>LinkTwo</a>";
It took me some time to find this answer on Stackexchange because I was using different search terms. I believe that the link suggested there is a more complete answer than the ones already given here:
How to build a web widget (using jQuery)
It covers:
ensure the widget’s code doesn’t accidentally mess up with the rest of the page,
dynamically load external CSS and JavaScript files,
bypass browsers’ single-origin policy using JSONP.

Categories