ProudNoob
ProudNoob

Reputation: 77

insert javascript in yii2 layout file

I want to insert a javascript to this link on my navigation bar, here is my code in layout file.

$userItems = [];

            if (Yii::$app->user->isGuest) {
                 $userItems[] = [
                    'label' => 'How It Works?',
                    'items' => [
                        ['label' => 'Video', 'url' => ['/site/howto']], //I want to insert javascript here
                        ['label' => 'Slide', 'url' => ['/site/index']],
                    ],
                ];
                $userItems[] = [
                    'label' => 'Support',
                    'items' => [
                        ['label' => 'FAQ', 'url' => ['/site/index']],
                        ['label' => 'Live Chat', 'url' => ['/site/index']],
                    ],
                ];
                $userItems[] = [
                    'label' => 'App Store', 'url' => ['/site/index']
                ];
            } else {
                $userItems = MenuHelper::getAssignedMenu(Yii::$app->user->id);
            }
            echo Nav::widget([
                'options' => ['class' => 'navbar-nav navbar-left'],
                'items' => $userItems,
            ]);

Where should I put my code? I can't find a place to put it in /site/howto link

Upvotes: 1

Views: 114

Answers (1)

Yasin Patel
Yasin Patel

Reputation: 5731

Try This:

$userItems[] = [
                    'label' => 'How It Works?',
                    'items' => [
                        ['label' => 'Video',
                          'options' => [
                            'onclick' => 'Myfunction();', // give javascript function name
                            ], 
                         'url' => ['/site/howto']], 
                        ['label' => 'Slide', 'url' => ['/site/index']],
                    ],
                ];

Implement function in javascript as you want

2nd way :

$userItems[] = [
                    'label' => 'How It Works?',
                    'items' => [
                        ['label' => 'Video',
                          'options' => [
                            'class' => 'test', // give class name here
                            ], 
                         'url' => ['/site/howto']], 
                        ['label' => 'Slide', 'url' => ['/site/index']],
                    ],
                ];

In javascript :

$('.test').on('click', function(event){
    // your code
});

Upvotes: 1

Related Questions