I created yii 1 application and used following script in order to navigate in view file:
$(function() {
$('a[href*="#"]:not([href="#"])').click(function() {
if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
if (target.length) {
$('html, body').animate({
scrollTop: target.offset().top
}, 1000);
return false;
}
}
});
});
But, when i created yii2 application and pasted this code, it did not work. Then, i created new menu_navigate.js js file and pasted code like
$(function() {
$('a[href*="#"]:not([href="#"])').click(function() {
if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
if (target.length) {
$('html, body').animate({
scrollTop: target.offset().top
}, 1000);
return false;
}
}
});
});
i registered this code in ThemeAsset using following code:
public $js = [
'Index/menu_navigate.js'
]
But, this code did not help me and it is not working. I could not manage to find any error. In console screen it is showing following error messageGET http://all/themes/CompanyProfile/Index/menu_navigate.js
(Not found)
Use '/Index/menu_navigate.js', that will help you to get correct path.
If this file is outside of web accessible directory, you need to set correct sourcePath
in asset bundle:
<?php
namespace app\assets;
use yii\web\AssetBundle;
class MenuNavigationAsset extends AssetBundle
{
public $sourcePath = '@bower/font-awesome'; // Replace with folder where "Index" folder is located. Path should be absolute, you can use aliases here.
public $js = [
'Index/menu_navigate.js',
];
}
Then it will be copied to web accessible directory and loaded from there. You can fild official docs for defining aliases here. It prevents you from hard coding absolute paths.
Otherwise (if file is in web accessible directory), set basePath
and baseUrl
properties:
<?php
namespace app\assets;
use yii\web\AssetBundle;
class MenuNavigationAsset extends AssetBundle
{
public $basePath = '@webroot';
public $baseUrl = '@web';
public $js = [
'Index/menu_navigation.js',
];
}
Check accurately that the path from where browser tries to load this js file and make sure file exists there if path is correct, otherwise correct path in your asset bundle.
Also check path for typos.
Official docs for working with assets is available here.