Loading an Image through Ajax on mouseover text - asp.net

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<title>Services</title>
<link rel="shortcut icon"
type="image/x-icon" href="css/images/favicon.ico" />
<script language="javascript">
var XMLHTTPRequestObj=false;
if(window.XMLHttpRequest)
{
XMLHttpRequestObj=new XMLHttpRequest();
}
else if(window.ActiveXObject)
{
XMLHttpRequestObj=new ActiveObject("Microsoft.XMLHTTP");
}
function getData(dataSource, divID)
{
if(XMLHttpRequestObj)
{
var obj=document.getElementById(divID);
XMLHttpRequestObj.open("GET", dataSource);
XMLHttpRequestObj.onreadystatechange = function() {
if(XMLHttpRequestObj.readyState == 4 &&
XMLHttpRequestObj.status == 200) {
alert("Inside the ready status "+dataSource);
if(dataSource=="ajaximport/1.jpg") {
alert("The if loop is working");
document.getElementById(
"targetDiv").innerHTML =
XMLHttpRequestObj.responseText;
var img = document.createElement('img');
alert("Variable img Recorded "+img);
img.onload = function (e){
alert("Loading Image");
document.getElementById(
"imgHolder").width=this.width;
document.getElementById(
"imgHolder").height=this.height;
document.getElementById(
"imgHolder").src=this.src;
}
img.onerror = function(e){
alert("Error processing Image. Please try again."+e);
}
img.src = XMLHttpRequestObj.responseImage;
}
else
obj.innerHTML=XMLHttpRequestObj.responseText;
}
}
XMLHttpRequestObj.send(null);
}
}
</script>
<!--[if IE 6]>
<link rel="stylesheet" href="css/ie.css" type="text/css" media="all" />
<![endif]-->
</head>
<body>
<!-- Content -->
<div id="content">
<!-- Shell -->
<div class="shell">
<h2>We at Creative bits 5 are plegded to serve you our best in.......</h2>
<table>
<th>
<div id="hold_left">
<ul>
<li><label>
<a href="#" onmouseover="getData('ajaximport/1.jpg','targetDiv')">
Graphic Designing
</a></label></li><br>
<li><label>
<a href="#" onmouseover="getData('text1.txt','targetDiv')">
Web Devlopment
</a></label></li><br>
<li><label>
<a href="#" onmouseover="getData('text1.txt','targetDiv')">
Logo Designing
</a></label></li><br>
<li><label>
<a href="#" onmouseover="getData('text1.txt','targetDiv')">
3D Walk-Through
</a></label></li><br>
<li><label>
<a href="#" onmouseover="getData('text1.txt','targetDiv')">
3D Modelling
</a></label></li><br>
<li><label>
<a href="#" onmouseover="getData('text1.txt','targetDiv')">
2D Presentations
</a></label></li><br>
</ul>
</div>
</th>
<th>
<div id="targetDiv">
This is target
<img id="imgHolder" src="" alt="This is where image will load" />
</div>
</th>
</table>
</div>
<!-- end Shell -->
</div>
<!-- end Content -->
</body>
</html>
Hi I am Using ASP for my web project. but I got stuck with a problem when I tried loading an image into a target division when a mouse is hovered over a text describing that image.
The division holding the text is on the left side (which describes the loading image)
On the right side is the Target division.
All is fine when I used it to load a text from a .txt file but The problem started when I tried modifying the same code for loading an image in the same division instead of the text
My code is as above

If the image file is a physical file stored on the filesystem then XMLHttpRequest may not be such a good idea to load the image.
I would suggest that in your javascript code you can create an image and set the src to the image path. that would load it and your image onload routines can also run. furthermore, you would get the benefit of browser caching of the image.
It would have made sense to use XMLHttpRequest in case your image was stored as a BLOB somewhere and you need some mechanism to retrieve it. in that case have a look at this link.
Handling images from XMLHttpRequest (with HTML and Javascript)
hope this helps.
EDIT 1(in response to comment): You can have a separate method for setting images via JavaScript.that way the images can be handled by a separate function while dynamic data through XHR can be handled separately.
<script language="javascript">
var XMLHTTPRequestObj = false;
if (window.XMLHttpRequest) {
XMLHttpRequestObj = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
XMLHttpRequestObj = new ActiveObject("Microsoft.XMLHTTP");
}
function getData(dataSource, divID) {
if (XMLHttpRequestObj) {
var targetDIV = document.getElementById(divID);
XMLHttpRequestObj.open("GET", dataSource);
XMLHttpRequestObj.onreadystatechange = function () {
if (XMLHttpRequestObj.readyState == 4 &&
XMLHttpRequestObj.status == 200)
{
targetDIV.innerHTML = XMLHttpRequestObj.responseText;
}
}
XMLHttpRequestObj.send(null);
}
}
function getImage(dataSource, divID) {
//create image element
var img = document.createElement('img');
//assuming divID has the target div id
img.onload = function (e) {
alert("Loading Image");
document.getElementById(
divID).width = this.width;
document.getElementById(
divID).height = this.height;
}
img.onerror = function (e) {
alert("Error processing Image. Please try again." + e);
}
//set the path here
img.src = dataSource;
var targetDIV = document.getElementById(divID);
//clear contents of target div
if (targetDIV.hasChildNodes()) {
while (targetDIV.childNodes.length >= 1) {
targetDIV.removeChild(targetDIV.firstChild);
}
}
//finally add the image as a child control to the div.
targetDIV.appendChild(img);
}
</script>
and call this by onmouseover="getImage('Image/1.jpg','targetDiv')
please note that this is pure javascript code. you can always use a JS library such as JQuery to do the same work in very few lines of code.

Related

onload on html tag before the script tag

I'm trying to get a function to run when some element on the page is loaded
<img src="" onload="myfunction()">
<footer>
<script src="main.js"></script>
</footer>
Now, the problem is that the page is trying to load the function before the js file is loaded
Do I have a solution other then loading the js file in the header??
I'd have a tiny function that just waits until the JS file is loaded, and then call the function in the JS file. Example:
<img src="" onload="stateCheck()">
<script>
let stateCheck = setInterval(() => {
if (document.readyState === 'complete') { // could use = 'interactive' too
clearInterval(stateCheck);
myfunction()
}
}, 100);
</script>
<script src="main.js"></script>

Blazor set CSS file based on request path

I'm attempting to switch out the css file on the fly - based on which part of the web-system the user is in (i.e. if the user is on mydomain/students/page then the page loads with students.min.css, rather than site.min.css).
I've tried doing it within the _Host.cshtml:
#page "/"
#namespace FIS2withSyncfusion.Pages
#addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
#{
Layout = null;
//sniff the requst path and switch the stylesheet accordingly
string path = Request.Path;
string css = "site.min.css";
if (path.ToLowerInvariant().StartsWith("/students"))
{
css = "students.min.css";
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Martin's Blazor Testing Site</title>
<base href="~/" />
<link rel="stylesheet" href="css/#(css)" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.20/lodash.min.js"></script>
<script type="text/javascript">
function saveAsFile(filename, bytesBase64) {
if (navigator.msSaveBlob) {
//Download document in Edge browser
var data = window.atob(bytesBase64);
var bytes = new Uint8Array(data.length);
for (var i = 0; i < data.length; i++) {
bytes[i] = data.charCodeAt(i);
}
var blob = new Blob([bytes.buffer], { type: "application/octet-stream" });
navigator.msSaveBlob(blob, filename);
}
else {
var link = document.createElement('a');
link.download = filename;
link.href = "data:application/octet-stream;base64," + bytesBase64;
document.body.appendChild(link); // Needed for Firefox
link.click();
document.body.removeChild(link);
}
}
</script>
</head>
<body>
<component type="typeof(App)" render-mode="ServerPrerendered" />
<script src="_framework/blazor.server.js"></script>
<div id="blazor-error-ui">
<environment include="Staging,Production">
An error has occurred. This application may no longer respond until reloaded.
</environment>
<environment include="Development">
An unhandled exception has occurred. See browser dev tools for details.
</environment>
Reload
<a class="dismiss">🗙</a>
</div>
</body>
</html>
However, it doesn't seem to hit this codeblock after the first load of the site; meaning whichever page they first landed on denotes the stylesheet for the entire site.
Do I have to put this codeblock on every page or is there another way of doing this?
another way you could approach this is to create components that respond to different styling that you desire. From there you have two options:
Create dedicated css associate with the component. From the docs
Create a class toggle in the code block of the component, similar to how the NavMenu works.
After further experimentation, I've found that adding this block:
#{
//sniff the requst path and switch the stylesheet accordingly
string path = navManager.Uri;
Uri uri = new Uri(path);
List<string> parts = uri.Segments.ToList();
string module = parts[1].ToLowerInvariant().Trim('/');
string css = "site.min.css";
if (module == "students")
{
css = "students.min.css";
}
}
<head>
<link rel="stylesheet" href="css/#(css)" />
</head>
To the top of MainLayout.razor works perfectly - so long as you remove the equivalent block from _Host.cshtml

paperjs onmouse events not firing

I have a canvas and trying to setup the onmousedrag and onmouseup events in paperjs.
The events never gets fired up when I try to draw something on the canvas object.
<!-- templates/index.html -->
<html>
<head>
<title>Annotation Tool</title>
<!-- CSS Files -->
<link rel="stylesheet" href="/static/node_modules/bootstrap/dist/css/bootstrap.min.css">
<link rel="stylesheet" href="/static/css/style.css">
<!-- Paper files -->
<script src="/static/node_modules/paper/dist/paper-full.min.js" charset="utf-8"></script>
<!--<script type="text/paperscript" src="/static/js/paperscript.js" charset="utf-8" canvas="myCanvas"></script>-->
<!-- Javascript files -->
<script src="/static/node_modules/jquery/dist/jquery.min.js" charset="utf-8"></script>
<script src="/static/node_modules/bootstrap/dist/js/bootstrap.min.js" charset="utf-8"></script>
<script src="/static/js/scripts.js" charset="utf-8"></script>
</head>
<body>
<script>
</script>
<div class="container">
<div class="row row-bordered">
<div class="btn-toolbar">
<button type="button" class="btn btn-primary" id="draw-line">Line</button>
<button type="button" class="btn btn-primary" id="draw-rect">Rectangle</button>
<button type="button" class="btn btn-primary" id="draw-poly">Polygon</button>
</div>
</div>
<canvas id="myCanvas"></canvas>
<!--<div class="row">-->
<!--<img src="/static/images/lena.png" alt="Italian Trulli">-->
<!--</div>-->
</div>
</body>
</html>
// scripts.js
var globals = {}
$(document).ready(function(){
alert('loaded')
paper.install(window)
paper.setup(myCanvas)
// tool.minDistance = 10;
var path;
path = new Path();
path.strokeColor = '#00000';
function onMouseDown(event) {
alert('test')
console.log('test')
path.add(event.point);
}
function onMouseDrag(event) {
// Every drag event, add a segment
// to the path at the position of the mouse:
path.add(event.point);
paper.PaperScript.load()
}
})
Your problem is that your code is executed in JavaScript context and you are defining named function onMouseDown and onMouseDrag and expect them to behave like in PaperScript context.
Quoting from documentation:
Installing Event Handlers
PaperScript recognises a couple of special event handlers when they are declared as global functions, while in JavaScript, these need to be manually installed on the appropriate object. Two such handlers are onFrame and onResize, which both belong to the View class. view is automatically created for us if we use the paperScope.setup(canvas) function as in the examples above. So all we have to do is install these handlers on the existing view object.
Working with Tools
Just like with the view handlers, PaperScript simplifies and hides the dealing with Tool objects by making the tool handlers seem global and by creating a tool for us on the fly if any of these handlers are present: onMouseDown, onMouseUp, onMouseDrag, onMouseMove, etc.
For convenience, as you are installing paper into local scope, you can directly set events handlers on the exposed view object.
Here is a simplified example of what you were trying to achieve (drag your mouse over the canvas to draw a path):
// Export paper variables into current scope.
// That's why we can use `view` or `Path` directly.
paper.install(window);
// Bound paper to canvas.
paper.setup('canvas');
var path;
// On mouse down...
view.onMouseDown = function(event) {
// ...init path.
path = new Path();
path.strokeColor = 'black';
};
// On mouse drag...
view.onMouseDrag = function(event) {
// ...add point to the path.
path.add(event.point);
};
html,
body {
margin: 0;
overflow: hidden;
height: 100%;
}
canvas[resize] {
width: 100%;
height: 100%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/paper.js/0.11.5/paper-core.min.js"></script>
<canvas id="canvas" resize></canvas>

How to Launch a new page from href

I currently use button and trying to launch a new window passing parameter from mypage to the new page like this
<input type="button" name="launchpg" id="launchpg" value="LaunchPage" onclick="launch_page('<%=list_process_url%>',this.form.myform.options[this.form.myform.options.selectedIndex].value);"/>
Javascript is as below:
<script type="text/javascript">
//call servlet
function launch_new_window(list_process_url,smart_id)
{
popupWindow = window.open(list_process_url+"&id="+id,'List Process Page',
'scrollbars = yes');
}
I am trying to replace button with href link as in..
document.location='main.jsp?PAGE=myPage.jsp&id='+this.form.myform.options[this.form.myfom.options.selectedIndex].value;
I would like to use the same javascript for launching a new window passing the parameter to the script function.
The code however doesn't seem to work as it says Form is not valid for href.
Add this to wherever you want to launch a new page from:
window.location.href = "pageName.html";
<head>
<title></title>
<script src="Scripts/jquery-2.1.1.min.js"></script>
</head>
<body>
<div id="main">
<script>
$(function () {
<!--Some Logic-->
<!--window.location.href = "NewWindowName.html";-->
}
$("#btnSave").click(function () {
openNewWindow();
});
function openNewWindow()
{
window.location.href = "NewWindowName.html";
}
});
</script>
<article>
<button id="btnSave">Save Data</button>
</article>
</div>
</body>
I found a solution to my question:
Open New Window

Why is afterRender never called?

Have a look at the following sample HTML. It is a simple KO foreach binding and a button to add a new item to the observableArray. The addition works fine and the new item shows up. However, the afterRender method is never called - not after the initial binding and not after a new item is added (and rendered). Why?
Fiddle: http://jsfiddle.net/CQNm6
HTML
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title></title>
<script type="text/javascript" src="http://knockoutjs.com/downloads/knockout-2.2.1.js"></script>
</head>
<body>
<div data-bind="foreach: data.things, afterRender: afterRenderTest">
<h1 data-bind="text: name"></h1>
</div>
Add New Thing
<script type="text/javascript">
var Thing = (function ()
{
function Thing(p_name)
{
this.name = ko.observable(p_name);
}
return Thing;
})();
var data =
{
things: ko.observableArray(
[
new Thing("Thing One"),
new Thing("Thing Two"),
new Thing("Thing Three")
])
};
function afterRenderTest(elements)
{
alert("Rendered " + elements.length + " elements.");
}
ko.applyBindings();
</script>
</body>
</html>
Your syntax is wrong because foreach binding either take an array or an object where you specify the additional events, arguments.
From the documentaiton:
Pass the array that you wish to iterate over. The binding will output
a section of markup for each entry.
Alternatively, pass a JavaScript object literal with a property called
data which is the array you wish to iterate over. The object literal
may also have other properties, such as afterAdd or includeDestroyed...
So you need write:
<div data-bind="foreach: { data: data.things, afterRender: afterRenderTest }">
<h1 data-bind="text: name"></h1>
</div>
Demo JSFiddle.

Resources