Embed same web widget multiple times with different data attribute values - javascript

I want to create a web widget that can be embedded multiple times on the same page but with different data attribute values so I can display different data according to the data attribute value.
For example, I want to embed mywidget.js file multiple times as follows:
<body>
<div>
<script src="script/mywidget.js" data-sport="soccer" id="widget-soccer">
</script>
</div>
<div>
<script src="script/mywidget.js" data-sport="tennis" id="widget-tennis">
</script>
</div>
</body>
My question is, inside the code in mywidget.js, how do I determine the correct script tag reference and read it's data attribute so I can use that value to fetch the corresponding data from a web service. I am using only jquery and javascript.
I want the widget to be embeddable on other users sites as well so all they do is embed using only the script tag and passing in the desired data attribute value without adding anything extra anywhere they need on their website.

This is not really a very good approach, as it is very inflexible. But given that <script> tags, when not deferred, halt parsing of the document while they execute, the current script tag will be the last in the DOM; so you can get the current sport inside your script by using this:
var sport = $('script').last().data('sport');
However, it would be much better to define a function in your external JavaScript file, and then invoke it when you need to instantiate your widget (EDIT: like in Lee Taylor's answer).

Why don't you do something like:
<head>
<script src="script/mywidget.js"></script>
</head>
<body>
<div><script>createMyWidget({sport : "soccer"} );</div>
<div><script>createMyWidget({sport : "tennis"} );</div>
</body>

I don't think you can. I know it's not that nice, but I would try:
<div><script>sport = "soccer";</script><script src="script/mywidget.js" id="widget-soccer"></script></div>
<div><script>sport = "tennis";</script><script src="script/mywidget.js" id="widget-tennis"></script></div>
and use sport in mywidget.js
Another approach could be that myscript.js is actually a dynamic "page", let's say with php, then you could use src="script/mywidget.js?sport=swimming", and in the php you would print:
sport = "<?php echo addcslashes($_GET['sport'], '"'); ?>";
But even better would be:
<script src="script/mywidget.js"></script>
<div><script>showWidget("soccer");</script></div>
<div><script>showWidget("basketball");</script></div>

I think you can use jQuery to find all script tags with src="script/mywidget.js" or something
$('script[src="script/mywidget.js"]')
And then you'll have an array of scripts tags that you can loop through and access the data property using jQuery's .data() method.

Related

Passing HTML value to embedded script

So I have a HTML file with an embedded script. A Java application sends a value to this HTML file. Now I wonder how to pass this value from the HTML down to the script. Is this even possible?
Here is the simplified HTML file with my approach:
<html>
<body>
<div id="test">
[VALUE_FROM_BACKEND] // prints "let valueFromBackend = 1234"
</div>
<script>
console.log(document.getElementById('test').value);
// should return: let valueFromBackend = 1234;
// actually returns: undefined
</script>
</body>
</html>
Unfortunately, I can't pass the value from the Java application directly to the script. I got the above approach from here, but this doesn't work.
Other solutions only focus on getting values from remote HTML pages, declaring the HTML files's source in the script tag. But since it is an embedded script here, this also seems not to work.
Does anyone know how to deal with the situation? Help will be much appreciated.
Only HTML input elements have a value in javascript. A div cannot have a value, which is why your code returns undefined.
To access the text inside a regular HTML element, such as a div, use element.innerText instead.
Here is a working code snippet you can try out:
console.log(document.getElementById('test').innerText);
<div id="test">
let valueFromBackend = 1234
</div>
As you want to get value of a div element, so the syntax is:
document.getElementById('test').innerHTML
Remember that getElementById().value works for input and use getElementById().innerHTML for elements like div

Interpret variable in Javascript file Laravel

I need to include a js file in my views.
But in this js file i need to interpret somes PHP variable.
Actually i do this :
#section('javascript')
<script>
alert("{{{test}}}");
</script>
#stop
But i REALLY need to do this :
#section('javascript')
{!! Html::script('js/test.js') !!}
#stop
test.js :
alert("{{{test}}}");
I need to declare a lot o variable. So my JS file will be very huge. And i don't want to show this directly in the source code.
How can i do ?
Thank you !
You can only pass the variable to the javascript like so:
#section('javascript')
<script>
var test = {{{$test}}};
</script>
#stop
then in your javascript file included at the bottom you can use it:
alert(test);
Let me just mention that this is not a great way of handling the passing variables from php to javascript.
When I need to do something like this, I usually create a meta tag on the page which would contain the alert information.
<meta name="someAlertValue" content="{{{ $test }}}" />
Then you can very easily grab that via jQuery.
var alert_text = $('meta[name=someAlertValue]').attr('content');
I find this approach to be much cleaner and maintainable than trying to drop php variables directly into your javascript.
I had the same problem, and wanted to have a stand alone js which will have bunch of variables taken from config() or even from database, multi-language, and will be configurable, or even will work with query parameters.
Maybe it's a hard way, but i've created a route:
Route::get('/js-modules/test.js',function(){ return view('js-modules.test');})->name('my_js);
So in the view resources/views/js-modules/test.blade.php you can put your js code together with your PHP stuff.
Or you can route it to a controller and have even more background work. it looks a bit slow (in the browser) on the first run , but second request it'll be cashed and retrieved as the regular js file
And now you can link it to any of your pages with
<script src="{{route('my_js')}}"></script>

Change title of web page according to form elements

I'm looking to change the title of an html page according to certain form elements, as well as some text found on that page. I found a good site describing how using Javascript can do almost what I need, located here: http://www.devx.com/tips/Tip/13469.
The problem with the script found there is that the option to change the title is restricted to the textarea, or if I try to include another element, I get an error message. I authored web page/form templates, nothing complicated, where the intended users, who, shall we say, are not very computer literate(one of them has never used computers), fill out certain textareas and drop-down options and then save the pages in an ARCHIVE folder. To make it easier for them, I would like to give them the luxury of saving the pages without having to type the relevant date and # (each form is basically one of a series of 59), essentially standardizing the titles of the saved pages which should make it easier to categorize them using another script in the future. Can the code below(the one found in the above web site) be extended to include more than one html item, such as the select drop-down options found below, and maybe something found inside elements such as a or div?
<HTML>
<HEAD><TITLE>Change Title Dynamically:</TITLE></HEAD>
<BODY>
<FORM action="" method=POST name="SampleForm">
<B>Enter Title for the window:</B>
<TEXTAREA NAME=WindowTitle ROWS=1 COLS=50></TEXTAREA>
<INPUT TYPE=BUTTON VALUE="Change Title" ONCLICK="javascript:UpdateTitle()">
</FORM>
<SCRIPT LANGUAGE="JAVASCRIPT">
<!--
function UpdateTitle()
{
document.title = document.SampleForm.WindowTitle.value;
}
</SCRIPT>
</BODY>
</HTML>
<SELECT>
<option>-----</option>
<OPTION>JAN</OPTION>
<OPTION>FEB</OPTION>
<OPTION>MAR</OPTION>
<OPTION>APR</OPTION>
<OPTION>MAY</OPTION>
<OPTION>JUN</OPTION>
<OPTION>JUL</OPTION>
<OPTION>AUG</OPTION>
<OPTION>SEP</OPTION>
<OPTION>OCT</OPTION>
<OPTION>NOV</OPTION>
<OPTION>DEC</OPTION>
</SELECT>
I would recommend jQuery to get the values of the fields you want to display in the title and set it. More info on jQuery can be found at http://jquery.com/
You can use a jQuery selectors to get the values of the fields and concatenate it accordingly. Something like this:
document.title = $('textarea').val() + ' - ' + $('select').val();

Alfresco- Pass variable values from js controller to freemarker

can anybody tell me what am I doing wrong?
I want to retrieve all my alfresco sites with this code (this should work):
model.sites = siteService.listSites(null, null, 0); // return type= List<Site>
And now i want to retrieve this list model.sites in my HTML freemarker template like this:
<body> ${sites} </body>
How can I view this sites list. I know i am getting it wrong in my ftl, but can't find a solution how to retrieve it.
You'll need to loop over the sites in your freemarker. Assuming you wanted a list of the site names, with commas between them, then your freemarker would instead want to look something like:
<body>
<#list sites as site>
${site.shortName}<#if site_has_next>,</#if>
</#list>
</body>

Playframework: Elegant way to pass values to javascript

Does anyone have an elegant solution to pass server values to javascript (that is not inline) in playframework? just like ${x} or &{'x'} inside html
Currently I can think of
<script type="text/javascript">
var x= ${x};
</script>
<script src="/public/javascripts/jsThatUsesX.js" type="text/javascript" ></script>
I'm thinking there is a better solution from play
It's not pretty, but that's the way I always end up doing it.
If the values that you're passing to JavaScript describe something in the DOM, you might consider using HTML 5 data attributes to place that information in the HTML. Then you can retrieve it with getAttribute. e.g. If your page is a blog post and you need to store the post ID you could use
<div class="post" data-post-id="77">
...
</div>
That way the data is separated out from the logic and you don't need to inline any JavaScript. You could also use a hidden form field.
What's wrong with that? I found myself doing things like
<script>
var trades = [${_trades.collect {models.Trade t -> t.price}.join(", ")}];
// ...
</script>
I like it the groovy way ;)

Categories

Resources