Reputation: 55
There are two main JS scripts. Both which are WORK as expected independently. One of them is for a menu (which is not in the HTML at the moment) The other is for a div that will change dynamically (in below HTML).
Both of these use $(document).ready(function ()
When I put them in seperate files they do not work. Put all functions under the same $(document).ready(function ()
it still does not work.
If i put them in the same file, as two independent scripts, only the top one will work as expected.
Any Ideas? I'm new to JS and i'm struggling to get my head around how the code is to be laid out.
JS:
(function ($) {
"use strict";
var mainApp = {
main_fun: function () {
$('#main-menu').metisMenu();
$(window).bind("load resize", function () {
if ($(this).width() < 768) {
$('div.sidebar-collapse').addClass('collapse')
} else {
$('div.sidebar-collapse').removeClass('collapse')
}
});
},
initialization: function () {
mainApp.main_fun();
}
}
$(document).ready(function () {
mainApp.main_fun();
});
}(jQuery));
SECOND JS
$(document).ready(function(){
var $content = $('.menu-content');
function showContent(type) {
$($content).hide();
$('#'+type).show();
}
$('.menu').on('click', '.menu-btn', function(e) {
showContent(e.currentTarget.hash.slice(1));
e.preventDefault();
});
showContent('about');
});
HTML:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<script src= "http://code.jquery.com/jquery-1.10.2.min.js" type="text/javascript"></script>
<script src="{{ url_for('static',filename='js/menu/custom.js') }}"></script>
<style>
div{
height: 200px;
width: 50%;
background-color: powderblue;
}
</style>
</head>
<body>
<ul class="menu">
<li><a href="#about" class="menu-btn">About</a></li>
<li><a href="#contact" class="menu-btn">Contact</a></li>
<li><a href="#cluster" class="menu-btn">cluster</a></li>
</ul>
<div id="about" class="menu-content">This is static - About</div>
<div id="contact" class="menu-content">This is static - Contact</div>
<div id="cluster" class="menu-content">cluster</div>
</body>
</html>
Expected Result - When I click on the buttons the single div should change
Upvotes: 0
Views: 100
Reputation: 6565
This could be a merged code, try this out:
$(document).ready(function(){
var $content = $('.menu-content');
function showContent(type) {
$($content).hide();
$('#'+type).show();
}
$('.menu').on('click', '.menu-btn', function(e) {
showContent(e.currentTarget.hash.slice(1));
e.preventDefault();
});
showContent('about');
mainApp.main_fun();
});
(function ($) {
"use strict";
var mainApp = {
main_fun: function () {
$('#main-menu').metisMenu();
$(window).bind("load resize", function () {
if ($(this).width() < 768) {
$('div.sidebar-collapse').addClass('collapse')
} else {
$('div.sidebar-collapse').removeClass('collapse')
}
});
},
initialization: function () {
mainApp.main_fun();
}
}
} (jQuery));
Upvotes: 1