passing value from javascript to partial view in mvc - javascript

the given below is my script
var selectedImage;
function select(image) {
var images = document.querySelectorAll('img');
var index = 0, length = images.length;
for (; index < length; index++) {
images[index].classList.remove('selected');
}
selectedImage = image.id;
image.classList.add('selected');
var image = document.getElementById(selectedImage);
var audioId = image.getAttribute('data-audio')
var audioElement = document.getElementById(audioId);
}
Now i want to pass the value of "audio element (which contains the Url of an audio fetched from database)" to another function which is defined in partial view. How to do this? please help.

Related

Cycling between two images

// this code is meant to create an array of two images and just circle through them to make it appear that a lightbulb is flashing on and off.
var imageArray = new Array();
var numImages=2;
// create new array to hold preload images; call this array imageArray
// create (global!) variable called numImages to hold total number of images;
//use for loop to populate imageArray
for (var i = 0; i < numImages; i++) {
imageArray[i] = new image();
imageArray[i].src="images/brightIdea"+(i+1)+"png"
//set image src property to image path, preloading image in the process
}
var i4_circleThru = 0; // global variable ( be careful) use for the function CicleThru()
function circleThru() {
//if browser does not support the image object, exit.
// write images, from imageArray to HTML doc
// call the setTimeout method on circleThru
}//end circleThru()
Because your end result is an html image, why not do it this way:
First, in your HTML:
<img id="imageID">
Then in your script:
var imageArray = [];
var numImages = 2;
for (var i = 0; i < numImages; i++) {
imageArray[i] ="images/brightIdea"+(i+1)+".png"
}
var i4_circleThru = 0;
var image = document.getElementById("imageId");
image.src = imageArray[i4_circleThru];
window.setInterval(function(){
i4_circleThru = (i4_circleThru+1)%numImages;
image.src = imageArray[i4_circleThru];
},1000);
A more complete example can be found here:
https://jsfiddle.net/FrancisMacDougall/fseswsro/

Looping through all the images on a page

2 Questions:
What will be the most officiant way to loop through all of the Images on a given page and open each one in a new tab.
Same idea but instead open in a new tab I would like to push different images instead of the given ones. The idea is to build a widget that will inject cat photos instead of the normal photos of websites.
I answered 2 in the code, and 1 in the comment of the first code block
var allImages = document.getElementsByTagName('img');
for(var i = 0; i < allImages.length ; i++) {
// to open all photos in new tabs:
// window.open(allImages[i].src, '_blank');
allImages[i].src = 'url_to_cat_image';
}
you can also do the same with jquery:
// change all photos to the same one:
var allImages = $('img');
allImages.attr('src', 'url_to_cat_image');
If you want each photo to be a different image, just replace the url_to_cat_image with a function that returns a random cat image in the first code block. For jquery, you can use .each and a random cat url function.
Here's a way of doing it with vanilla js. As mentioned in the comments, using the document.images node-list is the best method for getting the images, since it's a static list and need not be assembled in response to dom queries.
As mentioned, browsers will block the attempts to open new windowss, labelling them as pop-ups.
Here's a demo:
function forEachNode(nodeList, func) {
for (var i = 0, n = nodeList.length; i < n; i++) func(nodeList[i], i, nodeList);
}
function onBtnClicked() {
var diskUrl =
"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAA4AAAAOCAYAAAAfSC" +
"3RAAABdElEQVQoU22SLX/CMBCH/3E4IueorKNysh+hH6ESR93mqBuOuuEWiYyczB" +
"zycJPBIa+uU9nvmlD2wonmLulz78q+c4DIMH7Hk0UfOJ5/75KtrOWg9RxEwHqdfr" +
"xz9F9AXX9Ag8fXG3jssX6a3yUFwtCjqgnsDbK8gjIHDtnDHM6dsdks/oFXSNKuVg" +
"5VXoA+HZQxHLJsDvt+xu7lN/gTYgbqxqHMM3hPUGbvQ5YvYO0Ju91yivgX4oETWI" +
"AvBNV1PhTFAuZwwttrBO9B0u2qkVSzBG4jKL2yhxNYtDSSmx5HM0LyxgTVthEUkT" +
"qY+2mO0cHVUZrrOF8P1T5TKIpl8tTDHdvfnZ0BeqbBXN6WYiCoRsB8OUUiamEPHY" +
"qyhNlbYAZ0+w6eirRFUpSHapoIeu5Hj/TZwV8I5WOFZlUn0MA5DS3lANCSarOikE" +
"nRzDBHAi4dum1MV1IcI25beK6mvdUgKLHqlQsCSsRJpAlXIzUomvH+G/9qC1CEZi" +
"AJAAAAAElFTkSuQmCC";
forEachNode(document.images, function(elem) {
elem.oldSrc = elem.src;
console.log(elem.src);
window.open(elem.src);
elem.src = diskUrl
});
}
function onResetBtn() {
forEachNode(document.images, function(elem) {
if (elem.oldSrc != undefined) elem.src = elem.oldSrc;
});
}
<button onclick='onBtnClicked()'>Open pop-ups, change image sources</button>
<button onclick='onResetBtn();'>Reset</button>
<br>
<img src='data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAQAAAAHCAYAAAAvZezQAAAAKElEQVQIW2MUder+/3pfKSMDFDCCBEBsmCBcACaIIgASxK0CxQxkWwA6axnpT9J3PwAAAABJRU5ErkJggg==' />
<img src='data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAQAAAAHCAYAAAAvZezQAAAAJElEQVQIW2NkQAKiTt3/GWF8EAfEBgvAOGABZA52FVjNQBYEAPsjDS+SFXnjAAAAAElFTkSuQmCC' />
This is how you loop through all the images in a page.
I've also added example of opening in a new tab or replacing the source.
using native JavaScript no dependencies required.
// Array of cat photos
var arr = ['cat1.jpg', 'cat2.jpg', 'cat3.jpg'....]
var elem = document.getElementsByTagName('img');
for (var i = 0; i < elem.length; i++) {
var src = elem[i].getAttribute('src');
// Open in a new tab
if (src) window.open(src);
// Replace with a random cat photo
elem[i].src = arr[Math.floor(Math.random() * arr.length)];
}
Using vanilla javascript :
var images = document.querySelectorAll("img");
for(var i = 0;i < images.length;i++){
var image = images[i];
window.open(image.src,"_blank");
}
// changing for a kitty image
var images = document.querySelectorAll("img");
for(var i = 0;i < images.length;i++){
var image = images[i];
image.src = "http://placekitten.com/600/338";
}
However, if there are more than 1 image the browser will prevent that (see the popup message and allow that behaviour).

Cached data:url image not being loaded onto page

I made this code to take images from the page, convert them into data:url (what was it again... base64 encoded string), and save into localStorage. Then when the page is reloaded it should load the images from the localstorage and set the now empty image placeholders with the data:url image.
Issue now is that the images do not load and if you check the dimensions for the data:url image it is 300x150 when it was originally 40x40.
Here's the code:
var isChached, // Checks is the page's images have been chached into localStorage
isChangesd; // Checks if any images have been deleted or added to the
var img = [], // Used for loading from saved. img[] holds data:url image versions of the...
src = [], // ...images in src[]
saved = [], // All images that are to be saved are placed here
add = [], // New images are placed here
rem = []; // Images to be removed are placed here
var cnv = document.createElement("canvas");
ctx = cnv.getContext("2d");
if (window.localStorage) {
// Base Object
function Saver (width,height,path) {
this.width = width;
this.height = height;
this.src = path;
}
// These fucnctions will help you save, load, and convert the images to data:url
function save (_str) { // Saves to localStorage. _str is the key to which to save to. _path is the value that you plan on saving
var str = _str;
str += ""; // This way even if I input a none string value it is still converted into string
localStorage.setItem(str,JSON.stringify(saved));
} // Checks if this image isn't in the saved cache
function singleLoad(a,b) {
}
function loader (_str) { // Loads images from localStorage. _str is the key to be loaded
var str = _str;
str += ""; // This way even if I input a none string value it is still converted into string
var val = JSON.parse(localStorage.getItem(str)); // Save the now loaded and parsed object str into val
console.log('val '+JSON.stringify(val));
val.splice(0,1);
console.log('val2 '+JSON.stringify(val));
for (var i in val) { // Take loaded information and place it into it's proper position
img[i] = new Image(val[i].width,val[i].height);
img[i].src = val[i].src;
setTimeout(function () {
var imgs = document.getElementsByTagName("img"); // Get all images
for (var k = 0; k < imgs.length; k++) {
if (imgs[i].id == i) { // If the id is equal to the index name of the src[]
imgs[k].src = val[i].src;
imgs[k].height = img[i].height;
imgs[k].width = img[i].width;
console.log("array: "+imgs[i]+". img[i]"+img[i]);
}
}
},2000);
}
}
function addToAdd(_id,_path) { // Places on-page images into src[]
var id = _id;
id += ""; // Makes sure that the id variable is a string
var path = _path;
path += ""; // Makes sure that the path variable is a string
add[id] = new Image();
add[id].src = path;
var imgs = document.getElementsByTagName("img");
console.log(imgs);
for (var i = 0; i < imgs.length; i++) { // adds width and height attributes
if (imgs[i].id == id) {
setDim(add[id],imgs[i].width,imgs[i].height); // Send info to setDim()
}
}
}
// Not using this
function apply() { // takes images from img after being loaded and adds them to the page.
var images = document.getElementsByTagName("img");
for (var i = 0; i < images.length; i++) { // Check through the page's images
for (var k in img) { // Check through the img[] where the loaded images are now saved
if (images[i].id = k) { // Check if the id of the image on the page is
images[i].width = img[k].width;
images[i].height = img[k].height;
images[i].src = img[k].src;
console.log("source: "+images[i].src);
console.log("images: "+images[i]+". saved images "+img[k]);
}
}
}
}
function setDim(obj,w,h) { // Sets the dimension(width = w; height = h;) for obj (image object)
obj.width = w;
obj.height = h;
}
function saveToSrc(_id,_path,w,h) { // Places on-page images into src[]
var id = _id,data;
id += ""; // Makes sure that the id variable is a string
var path = _path;
path += ""; // Makes sure that the path variable is a string
src[id] = new Image();
src[id].src = path;
console.log("src image " + src[id]);
var imgs = document.getElementsByTagName("img");
console.log("page images " + imgs);
for (var i = 0; i < imgs.length; i++) { // adds width and height attributes
if (imgs[i].id == id) {
setDim(src[id],imgs[i].width,imgs[i].height); // Send info to setDim()
src[id].addEventListener("load",function() { // We convert images to data:url
console.log("saved image " + src);
ctx.drawImage(src[id],0,0,w,h);
data = cnv.toDataURL();
console.log("saved src " + data +" src width and height: "+src[id].width+","+src[id].height);
saved[id] = new Saver(src[id].width + "px",src[id].height + "px",data);
console.log("saver array: "+saved[id]);
})
}
}
}
function loadToPage(a) {
var imgs = document.getElementsByTagName("img"); // Get all images. Use this to change image src and dimensions
for (var i in a) { // Go through the a[] and load all the images inside onto page
for (var k = 0; k < imgs.length; k++) {
if (imgs[k].id == i) {
imgs[k].src = a[i].src;
imgs[k].height = a[i].height;
imgs[k].width = a[i].width;
}
}
}
}
// Here you place ID and path/location values into the src[] using the saveToSrc(). You can place the parameters in with quotation marks or without quotation marks
// **N.B** the location link will have to be changed to it's absolute form so that even if a 'scraper' gets our webpage the links still come to us \o/
if (localStorage.getItem("cached") == null) { // Check if the "cached" key exists.
// If it doesn't exist...
isCached = false;
localStorage.setItem("cached","true");
} else {
// ...If it does exist
isCached = true;
}
if (!isCached) {
// Now you take images from server and load onto page. And then save them.
window.onload = function() {
saveToSrc("1","img/1.png",40,40);
saveToSrc("2","img/2.png",40,40);
saveToSrc("3","img/3.png",40,40);
saveToSrc("4","img/4.png",40,40);
console.log("src "+src);
console.log("saved array " + saved);
loadToPage(src);
setTimeout(function() {
save('saved');
},3000)
}
}
/* Will Be Added Later. Same time as local host */
else {
window.onload = function (){
setTimeout(function() {
loader("saved");
apply
},3000)
}
}
}
I'm quite new to javascript(started using javascript this June, or was it May. anyways...) so please relax on the terminology.
To recap: Images saving correctly(-ish), not loading, and wrong image sizes saved

Send pictures to a new window

I'm trying to make a slideshow of pictures and send them to an another window. But after selecting images and pressing the button for showing slideshows, nothing happens. I'm using firebug to detect bugs and when I'm going wrong. But I'm not getting any error from firebug so I gotta ask you guys. This is my code.
var infoBox;
var formTag;
var imgUrlList;
var imgTextList;
var windVar;
var urlList;
var textList;
function init() {
var i;
infoBox = document.getElementsByClassName("outerBox");
for (i=0; i<infoBox.length; i++) {
infoBox[i].onmouseover = showInfoBox;
infoBox[i].onmouseout = hideInfoBox;
}
formTag = document.getElementsByTagName("input");
for (i=0; i<formTag.length; i++) {
formTag[i].onclick = checkedBox;
}
windVar = null;
imgTextList = [];
imgUrlList = [];
}
window.onload = init;
function showInfoBox() {
var showInfo;
showInfo = this.getElementsByClassName("innerBox")[0];
showInfo.style.visibility = "visible";
}
function hideInfoBox() {
var hideInfo;
hideInfo = this.getElementsByClassName("innerBox")[0];
hideInfo.style.visibility = "hidden";
}
function checkedBox() {
var ImgNode, ImgTag;
for (i=0; i<formTag.length; i++) {
imgNode = this.parentNode.parentNode.firstChild;
imgTag = imgNode.nextSibling
if (this.checked) {
imgTag.className = "markedImg";
}
else {
imgTag.className = "unmarkedImg";
}
}
}
function slideShowBtn() {
var url, i, filename;
imgUrlList.length = 0;
imgTextList.length = 0;
for (i=0; i<formTag.length; i++) {
if (formTag.checked) {
url = infoBox.firstChild.getElementsByTagName("img")[i].src;
filename = infoBox.firstChild.getElementsByTagName("span")[i].src;
imgUrlList.push(url);
imgTextList.push(filename);
}
else break;
}
newWindow(700,600,"slideshow.htm");
}
function newWindow(width,height,fileName) {
var windProporties;
windProporties = "top=100, left=100,toolbar=no,status=no,menubar=no,scrollbars=no,resizable=no,width=" + width + ",height=" + height;
if (windVar != null) if (windVar.closed == false) windVar.close();
windVar = window.open(fileName,"bildspel",windProporties);
}
The formTag variabel is from a checkbox-input-tag. And it's from that I decide which pictures are selected and will be moved to the new page. ImgTextList and imgUrlList are global variables that'll also be in the next window. infoBox is a reference to a div class which is called OuterBox and inside it is an another div-class named innerBox, it's in the innerBox classdiv which the img and span-tags are. The code for the slideshow is already written and I'm just writing code for sending the variables to it.
Edit: I should have been a little more informative. But here's the code for the slideshow part where window.opener is present. And I've added all the remaining code that's above. How do you embed files?
// JavaScript for the slideshow page
// ----- Global variables -----
var imgUrlList = window.opener.imgUrlList; // Array with filenames of selected images. Initialized to an empty array.
var imgTextList = window.opener.imgTextList; // Array with image texts of selected images. Initialized to an empty array.
var slideshowMenu = null; // Reference to the image menu.
var slideshowImg = null; // Reference to the slideshow img tag.
var slideshowText = null; // Reference to the tag for the image text.
// ---- Create the image menu and show the first image. Also attach event handlers. ----
function initSlideshow() {
// Create a image list from the content of the variable imgUrlList
var HTMLcode = "<select id='imgMenu'>";
for (var i=0; i<imgTextList.length; i++) {
HTMLcode += "<option>" + imgTextList[i] + "</option>";
} // End for
HTMLcode += "</select>";
document.getElementById("iMenu").innerHTML = HTMLcode; // Add the select and option tags to the HTML code
slideshowMenu = document.getElementById("imgMenu"); // Save a reference to the menu's select tag
slideshowMenu.selectedIndex = 0; // Select the first option in the menu
slideshowImg = document.getElementById("slideshowBox").getElementsByTagName("img")[0];
slideshowText = document.getElementById("slideshowBox").getElementsByTagName("div")[0];
// Show the first image
slideshowImg.src = imgUrlList[0];
slideshowText.innerHTML = imgTextList[0];
// Attach event handlers
var slideshowButtons = document.getElementById("slideshowForm").getElementsByTagName("input");
slideshowButtons[0].onclick = showPrevImage;
slideshowButtons[1].onclick = showNextImage;
slideshowMenu.onchange = showSelectedImage;
} // End initSlideshow
window.onload = initSlideshow;
// ---- Show previous image in the list (menu) ----
function showPrevImage() {
var ix = slideshowMenu.selectedIndex; // Index for the current image
if (ix > 0) { // If it's not already the first image
slideshowMenu.selectedIndex = ix-1;
slideshowImg.src = imgUrlList[ix-1];
slideshowText.innerHTML = imgTextList[ix-1];
}
} // End showPrevImage
// ---- Show next image in the list (menu) ----
function showNextImage() {
var ix = slideshowMenu.selectedIndex; // Index for the current image
if (ix < slideshowMenu.length-1) { // If it's not already the last image
slideshowMenu.selectedIndex = ix+1;
slideshowImg.src = imgUrlList[ix+1];
slideshowText.innerHTML = imgTextList[ix+1];
}
} // End showNextImage
// ---- Show selected image in the list (menu) ----
function showSelectedImage() {
var ix = slideshowMenu.selectedIndex; // Index for the selected image
slideshowImg.src = imgUrlList[ix];
slideshowText.innerHTML = imgTextList[ix];
} // End showSelectedImage
Um, you never do anything to send it. Either pass it as a querystring parameter or have the child reference a global variable in the opener.
var foo = window.opener.imgUrlList;

How to print dynamic contents of array at different positions in HTML5

I have to fetch data from the PHP web service in an array and then display it on HTML page using JavaScript. I have used a for loop to do so. But it doesn’t render proper output. Due to innerHTML the output gets replaced. Please help with your suggestions. Here is my code:
function jsondata(data){
alert("JSONdata");
var parsedata = JSON.parse(JSON.stringify(data));
var main_category = parsedata["main Category"];
for (var i = 0; i <= main_category.length; i++) {
menu = JSON.parse(JSON.stringify(main_category[i]));
menu_id[i] = menu['mcatid'];
menu_title[i] = menu['mcattitle'];
menu_img[i] = menu['mcatimage'];
pop_array.push(menu_id[i], menu_title[i], menu_img[i]);
//alert(pop_array);
for (var i = 0; i < main_category.length; i++) {
alert("for start");
var category = document.createElement("li");
document.getElementById("mylist").appendChild(category);
//document.getElementById("mylist").innerHTML='<table><tr><td>'+pop_array[i]+'</td></tr></table>';
document.write(pop_array.join("<br></br>"));
alert("for end");
}
}
}
Although I don't get why pop_array was used here but I assume that you are trying to display the category info as a li tag.
You should set category.innerHTML instead of document.getElementById("mylist").innerHTML.
function jsondata(data){
var parsedata = JSON.parse(JSON.stringify(data));
var main_category = parsedata["main Category"];
for (var i = 0; i < main_category.length; i++) {
var menu = main_category[i];
var category = document.createElement("li");
category.innerHTML = menu['mcattitle']; // construct your own html here
document.getElementById("mylist").appendChild(category);
}
}

Categories