How to get id of javascript's container? - javascript

I would like to get ID of javascript's container, for ex:
<div id="d_17j_a">
<script type="text/javascript">
alert("<ID of javascript's container here>");
// it will alert: d_17j_a
</script>
</div>
(ID of div is dynamic)
Thank for any suggestion !

So scripts are loaded sequentially, so you can get the parent node of a script element through:
var scripts = document.getElementsByTagName('script');
var me = scripts[scripts.length-1];
console.log('parent id', me.parentNode.id);

<script id="FindMe" type="text/javasctipt"> should work just fine using jQuery("#FindMe").parent().id
In pure javascript
document.getElementById("FindMe").parentNode.id

If you can add an id to your script tag you can grab the parent with Javascript after retrieving the script element.
<div id="d_17j_a">
<script id="myScript" type="text/javascript">
var parentId = document.getElementById("myScript").parentNode.id;
alert(parentId);
// it will alert: d_17j_a
</script>
</div>

Related

Elements added with innerHtml not affected by Javascript library

I've included a stripped down version of my code. I have a function which generates list elements, and the elements have children which should have a 3D effect from a library I've included. As is, the library is not affecting the elements generated, I assume because it is set by innerHtml or finishes generating after the script at the end is read. Is there a way to make this work?
<html>
<script type="text/javascript">
function createList() {
const list = ["https://placekitten.com/300/300", "https://placekitten.com/300/300"];
var output = '<ul>';
list.forEach((example) => {
output +=
`
<li>
<div class="img-container" data-tilt>
<img src="${example}" />
</div>
</li>
`;
});
output += '</ul>';
document.getElementById("catalog-container").innerHTML = output;
}
</script>
<body onload="createList()">
<div id="catalog-container">
</div>
<script type="text/javascript" src="vanilla-tilt.js"></script>
</body>
</html>
Create the elements before the library script runs. There are several options. One is to put your script tag before the library's, and avoid the body onload handler:
<body>
<div id="catalog-container">
</div>
<script>
function createList() {
// ...
}
createList(); // or remove the function entirely
</script>
<script src="vanilla-tilt.js"></script>
Another is to, instead, dynamically inject the library after your script runs. At the end of your function:
document.body.appendChild(document.createElement('script')).src = 'vanilla-tilt.js';
Or call the library on your new elements manually.

Is there a way to verify using liquid, if script tag is duplicated?

I would like to check using liquid language, if is there somewhere in the page, a script being called twice or more.
For example:
<script src="myscripts.js"></script>
<script src="myscripts.js"></script>
Is it possible using liquid or should I use javascript to validate?
I'm not sure about liquid, but if you wanted to go the JS route, this could work:
//locate all `<script>` tags and save the elements into an array
var scriptTags = [];
document.querySelectorAll('script').forEach(function(tag) {
scriptTags.push(tag)
});
//Put just the URLs of the script tags into an array
var scriptUrls = scriptTags.map(function(tag) {
return tag.src;
});
//Get a list of any URL that appears more than once
var duplicateUrls = scriptUrls.filter(function(url, i) {
return scriptUrls.indexOf(url) != i;
});
console.log(duplicateUrls);
<script src="dupe.js"></script>
<script src="other1.js"></script>
<script src="dupe.js"></script>
<script src="other2.js"></script>
<script src="other3.js"></script>

Javascript of selected php file won't load when using JQuery's load(file.php) method

I have a master container php file with a div container. Initially, the div container doesn't have any content or html children by default when page is loaded. I use JQuery to load php files to this div container when the user clicks a navigation item in the navbar.
landingpage.php
<?php
require_once 'navbar.php';
?>
<!DOCTYPE html>
<html>
<head>
<title>Admin | Dashboard</title>
<link rel="stylesheet" href="css/dashboard_admin.css">
</head>
<body>
<div class="wrapper">
<!-- CONTENT CONTAINER's content depends on what was clicked on navbar -->
<div class="container" id="content_container">
<div class="div_dashboardLabel" id="dashboard_Label">
<h2 id="label_Dashboard">Admin Dashboard</h2>
</div>
</div>
<!-- END OF CONTENT CONTAINER-->
</div>
<!-- end of wrapper-->
<script src="js/jquery-3.3.1.js"></script>
<script type="text/javascript">
var user = '<?php echo json_encode($user);?>';
var role = '<?php echo json_encode($role); ?>';
</script>
<script src="js/landingpage.js"></script>
</body>
</html>
landingpage.js
/* GLOBAL VARIABLES WITHIN THIS DOCUMENT*/
var div_content_container = $("#content_container");
var navitem_dashboard = $("#admin_dashboard");
var navitem_admin_account_management = $("#admin_accountmanagement");
var userObj = JSON.parse(user);
var roleObj = JSON.parse(role);
var logout = $('#logout');
/* END */
$(document).ready(function(){
loadDashboard(); // dashboard is loaded as default view.
navitem_admin_account_management.on("click",loadAccountManagement);
});
function loadDashboard() {
var url_admin_dashboard = 'view/admin_dashboard.php';
var url_teacher_dashboard = 'view/teacher_dashboard.php';
var url_student_dashboard = 'view/student_dashboard.php';
div_content_container.html('');
if (roleObj.rolename === 'Administrator') {
div_content_container.load(url_admin_dashboard);
} else if (roleObj.rolename === 'Teacher') {
div_content_container.load(url_teacher_dashboard);
} else if (roleObj.rolename === 'Student') {
div_content_container.load(url_student_dashboard);
}
}
function loadAccountManagement(){
var url = 'view/admin_accountmanagement.php';
div_content_container.html('');
div_content_container.load(url);
}
Everything works as expected for landingpage.php which uses landingpage.js for the front end. No problem.
The problem is when admin_accountmanagement.php file is loaded in div_content_container. The JS of admin_account_management.php doesn't seem to bind to elements:
function loadAccountManagement(){
var url = 'view/admin_accountmanagement.php'; // has its JS file
div_content_container.html('');
div_content_container.load(url);
}
For example, let's take url which is 'view/admin_accountmanagement.php' This page gets loaded within div_content_container when user clicks a navbar item Account Management
as in
<div class="wrapper">
<!-- CONTENT CONTAINER's content depends on what was clicked on navbar -->
<div class="container" id="content_container">
<!-- view/admin_accountmanagement.php loaded here -->
</div>
<!-- END OF CONTENT CONTAINER-->
</div>
There are no problems displaying the page or replacing the current element contained in the div_content_container. The problem is, the JS file attached to view/admin_accountmanagement.php doesn't seem to apply when view/admin_accountmanagement.php page is loaded in div_content_container
The view/admin_accountmanagement.php is loaded but the click events binded to the elements of view/admin_accountmanagement.php doesn't work. I know this because I tried to display an alert() message on $(document).ready()
admin_accountmanagement.php
<body>
<div>
<button class="button" id="btn_AddUser">
Add New User
</button>
</div>
<script src="js/admin_accountmanagement.js"></script> <!-- this JS doesn't seem to get binded when this page is loaded in the div_content_container -->
</body>
admin_accountmanagement.js
var btn_add_user = $('#btn_AddUser');
$(document).ready(function(){
alert("TEST"); //doesn't work no alert message.
btn_add_user.on("click",test); //doesn't work no alert message
});
function test(){
alert("testing"); //doesn't work. no alert message
}
I'm only able to display the page but when I click on the <button id="btn_AddUser"> nothing happens.
How can I solve this given the how I structured the loading of pages to div_content_container?
Thanks in advance.
Change your admin_accountmanagement.js to
var btn_add_user = $('#btn_AddUser');
alert('Account management js loaded'); // this should show alert
$(document).on("click",btn_add_user,test);
function test(){
alert("testing"); //doesn't work. no alert message
}
This method works because the binding is not dependent on "document ready" as document ready has already been fired when you loaded the parent page for the first time
#jordan i agree with #Magnus Eriksson as it is better to bind it on('event','selector','function') but make use of .off() before your .on() as you are playing with dynamic content which may cause multiple binding of the function. And if you are still not able to get the binding event to work you can try injecting the .js file in your page's head section after the load of your content like: $('head').append('<script src="admin_accountmanagement.js"></script>'). With your load() function in your js to bind the click event.
Or, your use the below code snippet:
function LoadContent()
{
var url = 'view/admin_accountmanagement.php';
var jssrc = 'js/admin_accountmanagement.js';
div_content_container.html('');
div_content_container.load(url);
if($('head').find('*[src="'+jssrc+'"]').length==0)
{
//the below approach have some consequences related to it as you will not be able to see the injected js in your developers tool's Sources(in chrome).
$('head').append('<script src="'+jssrc+'"></script>');
}
}
and then on your .js will look like this:
var btn_add_user = null;
$(window).load(function(){
alert("TEST");
btn_add_user = $('#btn_AddUser');
btn_add_user.off('click').on("click",test); //use .off('event') if load() is being called multiple times.
});
function test(){
alert("testing");
}

Javascript DataLayer Fetch from

I'd like to pull data from my HTML code into my dataLayer (Google Tag Manager).
The html code is something like this:
<body class="portal sessions" data-place="hun">...</body>
And the Javascript Code is something like this:
<script type="text/javascript">
var lang_log = document.getElementsByClassName("portal");
dataLayer.push({
"language_login":lang_log
})
</script>
What I'd try is to give to the lang_log variable the "hun" value and I'd try:
<script type="text/javascript">
var lang_log = document.getElementsByClassName("portal")['data-place'];
dataLayer.push({
"language_login":lang_log
})
</script>
But it's not working.
Any ideas?
Any help or advice is apprecaited, Thank you in advance.
document.getElementsByClassName("portal") returns an array-like collection of elements.
You can get the first element of this collection with document.getElementsByClassName("portal")[0].
To access the data attribute, use document.getElementsByClassName("portal")[0].dataset.place.
var AdataLayer = [];
var lang_log = document.getElementsByClassName("portal")[0].dataset.place;
AdataLayer.push({
"language_login":lang_log
})
console.log(AdataLayer);
console.log(AdataLayer[0].language_login);
<body class="portal sessions" id="portal" data-place="hun">...</body>
Found the solution:
the JS should be:
<script type="text/javascript">
var lang_log = document.getElementsByTagName("body")[0].getAttribute("data-locale");
dataLayer.push({
"language_login":lang_log
})
</script>
Still investigating in why the first version did not work!

Parse xml tag attributes using Javascript or Jquery?

I have one xml. Example XML is given below
<company sample="text">
<employee id="001" sex="M" age="20">Premshree Pillai</employee>
</company>
I need to get company attribute sample value
I am trying this method
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script type="text/javascript">
window.onload = function() {
var currLoanXml = '<company sample="text"><employee id="001" sex="M" age="20">Premshree Pillai</employee></company>';
var pic = $(currLoanXml).find('company').attr('sample');
alert(pic);
};
</script>
Its Shows Undefined in my alert box.
But i can also alert this child tag its working
var pic = $(currLoanXml).find('employee').attr('id');
alert(pic);
What is a problem. I need to get first tag attributes. Please help me.
you need to use filter() instead of find() here because company is the root element, ie currLoanXml refers to the company element. find will look for decedent elements only
var currLoanXml = '<company sample="text"><employee id="001" sex="M" age="20">Premshree Pillai</employee></company>';
var pic = $(currLoanXml).filter('company').attr('sample');
alert(pic);
Demo: Fiddle
You go too deep
$(function() {
var currLoanXml = '<company sample="text"><employee id="001" sex="M" age="20">Premshree Pillai</employee></company>';
var sample = $(currLoanXml).attr('sample');
console.log(sample);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Categories