EJS unable to access DOM elements causing undefined - javascript

I am trying to select DOM elements via VanillaJS or jQuery. Either way they are producing undefined within my ejs file.
I load all of my libraries at the top of ejs.
In middle of the page I have a simple
<% if (somevariable < 1) { %>
<!-- do something -->
<script> document.getElementById("showorders").style.visibility = "hidden" </script>
<% } %>
Further down the page I have a table with id "showorders".
All i want to do is set the visibility of the table to hidden if the statement is true. Else continue to run down the page and do normal process.
Why is the values undefined?

The problem might occur because in your script there is a reference to an element which does not exist.
You should wait for the DOM load event.
Vanilla
<% if (somevariable < 1) { %>
<!-- do something -->
<script>
document.addEventListener("DOMContentLoaded, function() {
document.getElementById("showorders").style.visibility = "hidden";
}, false);
</script>
<% } %>
jQuery
<% if (somevariable < 1) { %>
<!-- do something -->
<script>
jQuery(function() {
jQuery("#showorders").css("visibility", "hidden");
});
</script>
<% } %>

When the browser encounters a script tag it stops parsing the page and runs the script. This is how document.write is able to add content at the current position in the page.
If you want your script to run after the DOM has been fully parsed, you should listen for the DOMContentLoaded event.
document.addEventListener("DOMContentLoaded", function(event) {
document.getElementById("showorders").style.visibility = "hidden"
});

Related

Acessing Javascript variable in .aspx file showing elements conditionally

Having this .html snippet:
<body>
<div id="testDiv">
This always appears
</div>
<%
if(step==1)
{%>
html code
<% }
if (step==2)
{
%>
other html code
<% } %>
</body>
How can I access the variable "step", present in a .js file, imported using a script tag, in order to show HTML elements conditionally?
I am trying to somehow simulate the *ngIf function of Angular2, in AspX.
Thanks!
You can use it like this and create a javascript variable.
<script type="text/javascript">
var step = <%= step %>;
alert(step);
</script>
You can also use a ScriptManager
ScriptManager.RegisterStartupScript(Page, Page.GetType(), "setValue", "var step = " + step + ";", true);
In both cases step is available in .js files.

Using Rails, how do I execute a javascript file on a specific page in the application?

I am attempting to load a javascript file onto my rails application, but only for a specific page in my application, not the homepage. How would I get my javascript file to load for a specific page is using rails.
The javascript I have now, located in programs.js in assets/javascript, looks like this:
document.addEventListener('DOMContentLoaded', (event) => {
let program = document.getElementsByClassName('program-name')
console.log(program)
})
Again, the code itself works fine. The problem is that it executes for the homepage, and not for any particular page that I want it to. How would I go about getting the code to execute for a specific page within my rails application?
Why wouldn't you add the javascript tag to the View you want it to run on?
If you wanted a bit better rendering speed, you could add a end-of-page yield to your layout and then specify your javascript in the View like this:
layout/application.html.erb
<!DOCTYPE html>
...
<%= yield(:scripts) %>
</body>
</html>
view/.../index.html.erb
<!-- regular view code here -->
...
<% content_for :scripts %>
<%= javascript_tag do %>
document.addEventListener('DOMContentLoaded', (event) => {
let program = document.getElementsByClassName('program-name')
console.log(program)
});
<% end %>
<% end %>
An other way is to do the following:
app/views/layouts/application.html.erb
<body class="<%= controller_name %> <%= action_name %>">
<!-- This will add your page's controller and action as classes, for example, "blog show" -->
Then, in your script file, you can do the following:
if($('body').is('.yourcontroller.youraction'){
// Do something
}

Hide element depending on value of if/else statement not working

I have a Rails app that uses the LinkedIn Javascript API to authenticate users. What I'd like to do is hide an element depending on whether the user is signed up or not. I've tried a few things:
Put the code with the if/else statement at the bottom of the HTML before </body>
Check to see if document.cookie is an empty string instead of a more specific if/else
However, neither of these has hidden the element. If I go into my browser's console and paste in my code after the page is finished rendering, the element hides. So I thought this was a JavaScript load issue, but I must be doing something wrong. Can anyone shed some light on this?
Here's the code I've tried, none of which works:
<%= content_for(:script_footer) do %>
<script type="text/javascript">
// if ($('span.IN-widget:contains("inSign in with LinkedIn")').length > 0) {
// $('#select').hide();
// } else {
// $('#select').show();
// }
if (document.cookie == "") {
$('#select').hide();
} else {
$('#select').show();
}
</script>
<% end %>
And my application layout:
<!DOCTYPE html>
<html>
<head>
<title>rdtrip</title>
<%= stylesheet_link_tag "application", :media => "all" %>
<%= yield(:linked_in) %>
<%= javascript_include_tag "application" %>
<%= csrf_meta_tags %>
</head>
<body>
<%= yield %>
<%= yield(:script_footer) %>
</body>
</html>
Wrap your jquery/javascript code with:
$(function(){
// your code here
});
The JavaScript is executed before the DOM is ready, so it can't find #select yet.
Wrap it in either:
$(document).ready( function() {
// code
});
Or:
$(function() {
// code
});

!IsPostBack event from Javascript

I am using ASP.NET
I have to set the value of a variable [testVar] into Javascript on page load. only for the first time when the page load. Just like !IsPostBack event on code side.
From next postback this function of Javascript should not call. Please let me know how to implement it.
Add this line to your ASPX page:
<% if (!this.IsPostBack) %>
<% { %>
<script type="text/javascript">
document.getElementById("<%= this.timeVar.ClientID %>").value = '1/1/2010';
</script>
<% } %>

Refreshing a DIV element which has JSP code snippet inside

I have a JSP page where I am reading Session Attributes that I set in the Session.
I want to read the Session attributes in regular intervals. I don't want to reload the whole page instead I am just keeping my JSP Session read attributes in my DIV and trying to reload the DIV. But it is not reloading the DIV.
Here is my code base:
<html>
<head>
// Loading CSS and Script files
</head>
<body>
<div id="loadData" style='display:none;'>
<%
String strStatus = String.valueOf(session.getAttribute("Status")) ;
%>
</div>
</body>
<script type="text/javascript">
var reqStatus = '<%= strStatus %>';
$(this).load(function(){
setInterval(function() {
$("#loadData").load();
} ,1000);
});
$("#loadData").load(function(){
if(reqStatus == 'Done') {
// My Code goes here..
}
});
</html>
Any better ideas are also welcome.
JSP renders once, on the server, and is then sent to the client, after which the Java code does nothing. You can't put both the HTML/javascript code and the Java code in the same file if you want them to be loaded at different times / frequencies.
Put this into a separate .jsp file:
<%= String.valueOf(session.getAttribute("Status")) ; %>
Assume it's mapped to some url /checkStatus.jsp
Remove the loadData div because you don't need it anymore. Replace your javascript with:
var reloadStatus = function () {
$.ajax("/checkStatus.jsp", function (data) {
if (data == "Done") {
// Your code here
}
});
};
setInterval(reloadStatus, 1000);
Your JSP code is evaluated only once -- when the page first loads. When JSP code runs, HTML is generated and sent to the browser. You cannot "reload" a div like that; the JSP code will not run.
What you can do is put the JSP code into a separate filee and then use jQuery.load to load that page into a div:
jQuery(document).ready(function() {
setInterval(function() {
jQuery('#loadData').load('/status.jsp');
}, 1000);
}
status.jsp will contain just the one line:
<%= String.valueOf(session.getAttribute("Status")) ; %>
The code in a JSP is compiled/executed before the resulting HTML is sent to the browser. You can't reload part of the page as-rendered and expect it to change. You would probably need to make a hidden iframe and reload that completely (easy), or make a webservice to query the params (harder).

Categories

Resources