Javascript loading but not running - rails 3.1 - javascript

I have in my application layout file an external javascript file witch has several lines of code and at the end runs a function like BooManager.init() no big deal...
the problem is, it is not running the inside code on this javascript file.
this is how i use it:
<script type="text/javascript">
bb_bid = "1615455";
bb_lang = "en-US";
bb_keywords = "iphone4s, apple";
bb_name = "custom";
bb_limit = "8";
bb_format = "bbb";
</script>
<%= javascript_include_tag "http://widgets.boo-box.com/javascripts/embed.js" %>
but it didn`t do anything it was suposed to do...
i`ve tried in simple html file and it works... what am i doing wrong?
NOTE:
the default way in html is this:
<script type="text/javascript">
bb_bid = "1615455";
bb_lang = "en-US";
bb_keywords = "keywords, between, commas";
bb_name = "custom";
bb_limit = "8";
bb_format = "bbb";
</script>
<script type="text/javascript" src="http://static.boo-box.com/javascripts/embed.js"></script>
-- EDIT --
the result generated by rails:
<script type="text/javascript" src="http://static.boo-box.com/javascripts/embed.js"></script>

It's not evaluating the script when loading using the <%= method. I'm not familiar with that syntax, but from the effect, that's what it sounds like. It's treating the script as html rather than code.
jQuery has a script load function that will get a script dynamically from a URL and then eval() it to execute it.
UPDATED WITH SAMPLE CODE
Add jQuery to your app:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
Then use it to load your script:
$.getScript('http://widgets.boo-box.com/javascripts/embed.js');
UPDATE NUMBER 2
I was able to duplicate the problem in this fiddle: http://jsfiddle.net/7x2zT/4/
If what you are trying to accomplish is to get your parameters activated before the script shows the widget - the default one looks like a sidebar, whereas your parameters make it more of a banner, then just make sure you put your parameters above the <script src stuff.
If you must be able to load dynamically, then you're going to have to figure out where the bug lies in the embed code, or if there's some other activation method. That site's documentation doesn't seem to be in English, so I can't help with that.

Related

How can I pass an html img element to a javascript included file?

This is a question from a noob in javascript. I tried to find something similar the last two days but I didn't find. I try to pass an html image element to an external javascript file which I include to the rest html code. The javascript fade in and fade out an image. Because I want to use different images everytime, thus I want to have a function in an external javascript file.
What I did so far:
PHP and HTML:
<?php
if ($success){
echo"<link rel='stylesheet' href='js/jquery-ui-1.11.4-smoothness.css'>
<script src='js/jquery-1.11.3.js'></script>
<script src='js/jquery-ui-1.11.4.js'></script>
<img id='tick' src='tick.png'>
<script type='text/javascript' src='js/success_failure_signs.js'>
success_failure(tick);
</script>";
}?>
Javascript file has this code:
function success_failure(tick){
var x = tick;
x.fadeIn();
x.fadeOut(1000);
}
The browser's console doesn't give any error.
It seems that the function success_failure doesn't get the image.
What is wrong on this code and how can I fix it?
Thank you in advance!
You haven't defined tick when you make your function call. Try this...
<script type="text/javascript" src="js/success_failure_signs.js">
</script>
<script type="text/javascript">
var tick = $("#tick");
success_failure(tick);
</script>
EDIT: I've also separated the inclusion of the script and your code to call it into two separate script tags.
maybe passing the image to the script is the wrong way of thinking here.
Most of the time with Javascript for web pages the JS gets the image from the HTML site itself.
You are already including jQuery so look into how to get an element from the page with jQuery.

Prepare jquery before jquery and page load

I have recently discovered the new trend of including all .js script at the end of the page.
From what i have read so far seems pretty ok and doable with an exception.
The way I am working is using a template like:
<html>
<head>
<!-- tags, css's -->
</head>
<body>
<!-- header -->
<div id="wrapper">
<?php
include('pages/'.$page.'.php');
?>
</div>
<!-- footer -->
<!-- include all .js -->
</body>
</html>
Now, if I want to use this example on my page http://www.bootply.com/71401 , I would have to add the folowing code under my jquery inclusion.
$('.thumbnail').click(function(){
$('.modal-body').empty();
var title = $(this).parent('a').attr("title");
$('.modal-title').html(title);
$($(this).parents('div').html()).appendTo('.modal-body');
$('#myModal').modal({show:true});
});
But that would mean I either use that in every page - even if I do not have use for it, either generate it with php in the $page.'php' file and echoing it in the template file, after the js inclusion.
I am sure though, better methods exist and I don't want to start off by using a maybe compromised one.
Thanks!
Please avoid using inline scripts as they are not good maintainable and prevent the browser from caching them. Swap your inline scripts in external files.
Fore example you could put all your JavaScript in one file an check the presence of a specific element before initialize the whole code. E.g.:
$(document).ready(function(){
if($('.thumbnail').length) {
// your thumbnail code
}
});
A better way to execute "page specific" JavaScript is to work with a modular library like requirejs. You can modularize your scripts depending on their functionality (like thumbnails.js, gallery.js etc.) and then load the necessary script(s) depending e.g. on the existence of an element:
if($('.thumbnail').length) {
require(['ThumbnailScript'], function(ThumbnailScript){
ThumbnailScript.init();
});
}
The best way you can go is create a separate file for this code.
Let's name it app.js. Now you can include it under the jQuery inclusion.
<script type="text/javascript" src="app.js"></script>
This will prevent code repeat.
One more thing, pull all the code in $(document).ready(). Here is an example. So your app.js file will look like this:
$(document).ready(function(){
$('.thumbnail').click(function(){
$('.modal-body').empty();
var title = $(this).parent('a').attr("title");
$('.modal-title').html(title);
$($(this).parents('div').html()).appendTo('.modal-body');
$('#myModal').modal({show:true});
});
})

How do I load a specific javascript file or javascript code into an HTML document?

Here's what I'm trying to do;
I have this HTML code:
<div id="background-color-random">
DIV CONTENT
</div>
And this javascript:
$(document).ready(function() {
var colors = ["#FFA347", "#FF5050", "#FF66FF", "#6699FF", "#00FF99"],
selectedColor = colors[Math.floor(Math.random()*colors.length)]
header = $("div#background-color-random");
header.css("background-color", selectedColor);
});
I want to impliment this on an HTML page. I know that you can load up a *.js file by using the script tags with src="..". But that doesn't seem to work.
The javascript creates a random color and then applies that to the background of a given 'div' in the HTML.
Now, I'm not good with javascript, so please be patient with me and simple answers are needed :)
I need to be able to get the javascript to load when requested from the HTML and then apply itself to the div with id="..".
You have a syntax error (missing a comma):
selectedColor = colors[Math.floor(Math.random()*colors.length)]
header = $("div#background-color-random");
Should be
selectedColor = colors[Math.floor(Math.random()*colors.length)],
header = $("div#background-color-random");
You are using jQuery, not pure javascript. That's a good thing...
but you also must add the jQuery library in your head tags, like this:
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
</head>
You also need to put semi-colons (or commas, as RobM has corrected me, if between var assignments) at the end of each instruction. See line 3 in your code example.
If you want your js/jQuery code in a separate file, you can load the script code like this (again, usually done in the <head> tags):
<script src="filename.js" type="text/javascript"></script>
Or, you can include the js/jQ in the <head> tags of your document, like this:
<script type="text/javascript">
$(document).ready(function() {
var colors = ["#FFA347", "#FF5050", "#FF66FF", "#6699FF", "#00FF99"],
selectedColor = colors[Math.floor(Math.random()*colors.length)],
header = $("div#background-color-random");
header.css("background-color", selectedColor);
});
</script>
If including the script as an external file, you leave out the <script></script> wrapper from that file.

How to call external JavaScript function in HTML

I have a small chunk of code I can't seem to get working. I am building a website and using JavaScript for the first time. I have my JavaScript code in an external file 'Marq_Msg.js' which looks like this:
var Messages = new Array();
Messages[0] = "This is message 1";
Messages[1] = "This is message 2";
Messages[2] = "This is message 3";
Messages[3] = "This is message 4";
function scroll_messages()
{
for (var i = 0; i < Messages.length; i++)
document.write(Message[i]);
}
and in my HTML file 'Index.html' I am trying to call it like this:
<div id="logo">
<marquee scrollamount="5" direction="left" loop="true" height="100%" width="100%">
<strong><font color="white"><script src="Marq_Msg.js">scroll_messages()</script></font></strong>
</marquee>
</div>
The 'logo' div is a CSS piece that I'm trying to marquee inside of. If I put the code embedded inside the 'head' tag and call it, it works perfectly! There are a few other things id like to do with this code (like space the messages out a little) but I can't get the code to work in the first place. I've also tried adding:
<script src="Marq_Msg.js"></script>
in the 'head' tag with a separate call, that was a no go. I also tried instead using:
<script type="text/javascript" src="Marq_Msg.js">scroll_messages()</script>
Hell, i even had the function try returning a string (even hardcoded a simple "hello" to be returned) but that didnt work either with and without the 'type':
//Marq_Msg.js
function scroll_messages()
{
return "hello";
}
//index.html
<script type="text/javascript" src="Marq_Msg.js">document.write(scroll_messages())</script>
What am I missing? Any help would be greatly appreciated!! I've looked all over Google, and every site I find wants to do it using some 'form'. I just want messages to be displayed across, no form attached.
If a <script> has a src then the text content of the element will be not be executed as JS (although it will appear in the DOM).
You need to use multiple script elements.
a <script> to load the external script
a <script> to hold your inline code (with the call to the function in the external script)
scroll_messages();
In Layman terms, you need to include external js file in your HTML file & thereafter you could directly call your JS method written in an external js file from HTML page.
Follow the code snippet for insight:-
caller.html
<script type="text/javascript" src="external.js"></script>
<input type="button" onclick="letMeCallYou()" value="run external javascript">
external.js
function letMeCallYou()
{
alert("Bazinga!!! you called letMeCallYou")
}
Result :
If anyone still has the reference error is probably because you are loading your Javascript with defer, or it's in the bottom of the body so when the function gets called your function still doesn't exist.

Calling javascript functions from view in Rails 3

I am new to Rails and I have a pretty simple problem with calling javascript functions from within a view. In Rails 2 I would do...
= javascript_tag "name(arguments)"
where the javascript function "name" was located in my application.js file. However, this does not appear to work in Rails 3? Or am I missing something? I have been searching Google for some time without finding an answer.
UPDATE:
OK, so I looked at the source of the two different ways (using the javascript_tag and the haml javascript filter) as suggested. And this is very strange because the html source appears to be identical? Apart from a difference in double and single quotes in declaring the script type.
FIRST: using the javascript_tag which does not work
= javascript_tag "number_interval(#{fact.current_value}, #{fact.growth_per_second}, #{fact.decimal_number}, '#{dom_id(fact, "number")}'"
Source...
<div id='number_number_interval_727'>loading</div>
<script type="text/javascript">
//<![CDATA[
number_interval(6952596670.36814, 2.33002440293917, 0, 'number_number_interval_727'
//]]>
</script>
SECOND: using the haml javascript filter and it works
:javascript
number_interval(#{fact.current_value}, #{fact.growth_per_second}, #{fact.decimal_number}, '#{dom_id(fact, "number")}')
Source...
<div id='number_number_interval_727'>loading</div>
<script type='text/javascript'>
//<![CDATA[
number_interval(6952596917.02179, 2.33002440293917, 0, 'number_number_interval_727')
//]]>
</script>
Well, I guess I'll just stick with the haml filter!
You have a syntax error:
= javascript_tag "number_interval(#{fact.current_value}, #{fact.growth_per_second}, #{fact.decimal_number}, '#{dom_id(fact, "number")}'"
is missing the closing parenthesis for the number_interval function. I think that it should be:
= javascript_tag "number_interval(#{fact.current_value}, #{fact.growth_per_second}, #{fact.decimal_number}, '#{dom_id(fact, "number")}')"
A friend of mine pointed me to the fact that there is a javascript helper in haml. Apparently, I can call javascript functions by using...
:javascript
name_of_function(arguments)
This works, but of course only with haml.
Check out the right syntax on link text
and Check if you have included the javascript defaults in your file.As this working for me in RAILS 3 also
Silly question but... is application.js included in your layout?
One option to try is to hand-code the js function-call into your view in "real" javascript - just to see if it works. eg
<script type="text/javascript">
name(arguments)
</script>
Then you can be sure it's not the js itself (or lack thereof) at fault.

Categories

Resources