I am using Magento 2, in my case I want to add an element after another using jQuery, can anyway tell me how to it, the best practice please
For example i want to insert a div with class 'one' after another div with class 'two'
$(".one").insertAfter(".two");
thank you in advance !
-
1check this devdocs.magento.com/guides/v2.4/javascript-dev-guide/javascript/…fmsthird– fmsthird2020年12月19日 02:43:38 +00:00Commented Dec 19, 2020 at 2:43
-
1try this magento.stackexchange.com/a/306834Msquare– Msquare2020年12月19日 03:58:24 +00:00Commented Dec 19, 2020 at 3:58
1 Answer 1
To use jQuery in Magento you need to add require before using jQuery, like this:
<script>
require([
'jquery'
], function($){
$( "<div class='one'>Test</div>" ).insertAfter( ".inner" );
});
</script>
Here is the detail of how insertAfter works is here: https://api.jquery.com/insertafter/
#Edited
If you want to do it in js level, then you don't need require you can use this criteria to add your js.
Add your js file in app/code/Vendor/Module/view/frontend/web/js/your_js_file.js
then add requirejs-config.js in app/code/Vendor/Module/view/frontend/requirejs-config.js
content of requirejs-config.js will be:
var config = {
paths: {
'myfile': 'Vendor_Module/js/your_js_file'
},
shim: {
'myfile': {
deps: ['jquery']
},
}
};
Now you can use any jQuery functions in your file without using require
-
can i do this by creating a folder js to declare it into the file .js ?coding mv– coding mv2020年12月20日 14:11:09 +00:00Commented Dec 20, 2020 at 14:11
-
Yes you can do thisShoaib Munir– Shoaib Munir2020年12月20日 15:33:25 +00:00Commented Dec 20, 2020 at 15:33
-
can you update your answer plz to see howcoding mv– coding mv2020年12月20日 17:54:26 +00:00Commented Dec 20, 2020 at 17:54
-
see updated answerShoaib Munir– Shoaib Munir2020年12月21日 06:13:30 +00:00Commented Dec 21, 2020 at 6:13
Explore related questions
See similar questions with these tags.