0

Trying to dynamically change src attribute for js file.

<script id='mod' src="arts.js"></script>
<script src="main.js"></script>

inside arts.js I have:

$(document).on('click', function(){
    console.log('arts');
});

Inside banns.js I have:

$(document).on('click', function(){
    console.log('banns');
});

Inside the main.js I have:

$(document).on('contextmenu', function(){
    $('#mod').attr('src', 'banns.js');
});

After a right click I'm expecting the next click to write banns but it doesn't work.

Is it possible (without reloading the page)?

2
  • can you please specify the backend programming language because you can do it so easy if you are using something like dotnet razor Commented Dec 8, 2019 at 11:13
  • @moathnaji this is a classic php website Commented Dec 8, 2019 at 11:15

1 Answer 1

2

Changing the src of an existing script tag already in the DOM won't do anything. Instead, create another script tag, set its src, and append it to the DOM.

This won't negate whatever the previous script tag did, though - if you want to disable the click listener added previously, you'll need to do so explicitly:

document.body.appendChild(document.createElement('script')).src = 'banns.js';

and, inside banns.js, before setting the new click listener:

$(document).off('click');
Sign up to request clarification or add additional context in comments.

2 Comments

I need to off not only click but also contextmenu, drag... and everything from the previous file.
If the cleanup you have to do isn't completely trivial, it'd probably be better for the first script tag to expose a function that does that - that way, the script that creates the functionality can also remove the functionality. Eg function disableArts() { $(document).off('click').off('contextmenu')... There's no way to completely revert what the other script did automatically without replacing the page, which takes longer and often isn't desirable (like you said).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.