I want to move my JavaScript code to an external js file and use it within my View, as I want to "clear up/neaten up" my code on my page a bit, as I am using a lot of Javascript.
Before I post my code, what is best practice ? Keeping all the JavaScript in the View, or by creating an external js file and putting the code in there instead ?
Below is part of my code in my View(I have left the rest out as it follows the same structure and I dont want to unnecessarily add too much code here) :
@section scripts
{
<script type="text/javascript">
$('#aboutme_menu').on('click', function (event) {
var editable_elements = document.querySelectorAll("[contenteditable=true]");
for (var i = 0; i < editable_elements.length; i++) {
editable_elements[i].setAttribute("contentEditable", false);
editable_elements[i].style.background = "#F0F0F0";
editable_elements[i].style.borderColor = "#F0F0F0";
}
var employmentcancelbutton = document.getElementsByClassName('employment-cancel-button'), i;
for (var i = 0; i < employmentcancelbutton.length; i++) {
employmentcancelbutton[i].style.visibility = 'hidden';
}
$('.employment-edit-button').html('Edit');
$(".employment-edit-button").prop('disabled', false);
});
$('#employment_menu').on('click', function (event) {
var editable_elements = document.querySelectorAll("[contenteditable=true]");
for (var i = 0; i < editable_elements.length; i++) {
editable_elements[i].setAttribute("contentEditable", false);
editable_elements[i].style.background = "#F0F0F0";
editable_elements[i].style.borderColor = "#F0F0F0";
}
document.getElementsByClassName('aboutme-cancel-button')[0].style.visibility = 'hidden';
$('.aboutme-edit-button').html('Edit');
$(".aboutme-edit-button").prop('disabled', false);
});
</script>
}
I have tried by adding this code as is(Excluding the @Section
and <script>
Tags) into an external js file(UserProfile.js) and called the following on the top and bottom of the View and its not executing the code.
<script src="~/Scripts/UserProfile.js"></script>
Is there something else I need to add in the js file ? What am I missing ?
Please correct me if I am doing anything wrong or not following best practices.
EDIT 1
@satpal lead me in the right direction, I wrapped my code in my js file in the following : $(window).load(function () {
and then it worked.
Why does this work, but not $(function () {
or $(document).ready(function () {
?
Thank you.