Move jquery script out of main page...

User 315488 Photo


Registered User
90 posts

I'm working on building a responsive web site. To do that I needed the menus to be responsive too. I know there are many ways to do it, but I found a jquery script that creates a Select menu which works quite well for me.

Currently, I have the script on every page in the web site. Is there some way to put the script in a file in a subfolder and just link to it in each web page?

Here is the link to the site I'm testing now:
http://www.upctraining.rccomputersolutions.biz/

Here is the code I'm using in each page:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script>
$(function() {
$("<select />").appendTo("nav");

$("<option />",
{
"selected": "selected",
"value" : "",
"text" : "Site Menu" // default <option> to display in dropdown

}).appendTo("nav select");

$("nav a").each(function()
{
var el = $(this);
// my changes start
if(el.parents(".submenu").length) {
$("<option />", {
"value" : el.attr("href"),
"text" : "-- " + el.text()
}).appendTo("nav select");
} else {
$("<option />", {
"value" : el.attr("href"),
"text" : el.text()
}).appendTo("nav select");
}
});

$("nav select").change(function()
{
window.location = $(this).find("option:selected").val();
}); });
</script>


I would like to use something like I use for links to the style sheets.
Is that possible and if so, how is it done?

Thanks
User 187934 Photo


Senior Advisor
20,247 posts

Yes there is.
Paste this code into a blank page and name it myscriptname.js
$(function() {
$("<select />").appendTo("nav");

$("<option />",
{
"selected": "selected",
"value" : "",
"text" : "Site Menu" // default <option> to display in dropdown

}).appendTo("nav select");

$("nav a").each(function()
{
var el = $(this);
// my changes start
if(el.parents(".submenu").length) {
$("<option />", {
"value" : el.attr("href"),
"text" : "-- " + el.text()
}).appendTo("nav select");
} else {
$("<option />", {
"value" : el.attr("href"),
"text" : el.text()
}).appendTo("nav select");
}
});

$("nav select").change(function()
{
window.location = $(this).find("option:selected").val();
}); });

Then in all of your pages you'll have this.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script src="myscriptname.js"></script>
I can't hear what I'm looking at.
It's easy to overlook something you're not looking for.

This is a site I built for my work.(RSD)
http://esmansgreenhouse.com
This is a site I built for use in my job.(HTML Editor)
https://pestlogbook.com
This is my personal site used for testing and as an easy way to share photos.(RLM imported to RSD)
https://ericrohloff.com
User 315488 Photo


Registered User
90 posts

Of course - I knew that, but for some reason I couldn't get my mind wrapped around it.

Thanks,
:)

Have something to add? We’d love to hear it!
You must have an account to participate. Please Sign In Here, then join the conversation.