Dynamically populating image source with multiple instances of a JavaScript function - javascript

The popup in my fiddle works great except if i want to make more than one, i have to create multiple divs with multiple images and multiple IDs, which works fine but is time consuming and messy.
Edit: Each popup will have a different image
My goal is to:
1) Still create multiple IDs/images for each popup, but make a function where the script figures out the IDs dynamically so i'm not making a separate function for each ID.
OR
2) Create the whole popup HTML markup in javascript which will allow me to dynamically populate the image source in the popup with a data-attribute. When the link is clicked, it will create the popup and the image src in the popup can be dynamically populated with a data-src from that link.
Are any of these methods in the right direction? I need to use pure JS.
http://jsfiddle.net/6sh0dogr/5/
Basic JS function from fiddle:
var popup = document.getElementById('light');
var background = document.getElementById('fade');
function popit() {
popup.style.display = 'block';
popup.style.top = parseInt(pageYOffset, 10) + 150;
background.style.display = 'block';
}
function closeit() {
popup.style.display = 'none';
background.style.display = 'none';
}

Give your divs id like this:
element.id = "image_div"+Math.round(Math.random()*10000);
Now you can select all divs with:
var nodeList = document.querySelectorAll("div[id*='image_div']");
for (var i = 0; i < nodeList.length; ++i)
{
nodeList[i].addEventListener("click", popit.bind(null, nodeList[i].id), false);
}
div[id*='image_div'] is a selector. *= means contains. So this selector selects all div elements with id that contains image_div.
Now we can attach an event handler (click) to all divs using a for loop that iterates over the nodeList. The id of the div is passed on through the bind function to the function popit.
function popit(popId) {
var node = document.getElementById(popId);
popup.style.display = 'block';
popup.style.top = parseInt(pageYOffset, 10) + 150;
background.style.display = 'block';
}

Related

Show a hidden DIV when jQuery runs (and hides another DIV) [duplicate]

This question already has answers here:
Show/hide 'div' using JavaScript
(15 answers)
Closed last month.
I've created a script that hides a DIV Class if it contains the text "No Event Found" or "Error". This part is working great, however when this happens I would like a hidden DIV ID to load in it's place. (#brxe-akqmjs)
<script>
const divs = document.getElementsByClassName('etn-not-found-post');
for (let x = 0; x < divs.length; x++) {
const div = divs[x];
const content = div.textContent.trim();
if (content == 'No Event Found' || content == 'Error') {
div.style.display = 'none';
}
}
</script>
How do I go about getting this to load correctly? The DIV I want to show is set to display:none.
Many thanks in advance.
I have tried adding if statements but this only results in the original code breaking.
You can simply using jquery hide() and show() method to hide and show the content. Here I rewrite the function in jquery format.
<script>
const divs = $('.etn-not-found-post');
for (let x = 0; x < divs.length; x++) {
const div = divs[x];
const content = div.textContent.trim();
if (content == 'No Event Found' || content == 'Error') {
div.hide();
}else{
div.show();
}
}
</script>
It depends on how that hidden DIV with ID been implemented.
Let me try to cover two approaches:
DIV is hidden with css using display: none;
DIV is hidden using attribute hidden
For both cases, first get the element reference by ID. For e.g.
var divWithID = document.getElementById("divWithID");
Now for case 1,update the style property.
dovWithId.style.display = "block";
For case 2, set the hidden attribute value to false
divWithID.setAttribute("hidden", false);
Hope this helps and clarifies your question.

Collapsible not Working [JSFiddle demo Included]

I am trying to get this collapsible to function normally and show the first set of information when the page is loaded, make it disappear when the user presses "read more", and show new information.
<script>
var coll = document.getElementsByClassName("collapsible");
var i;
for (i = 0; i < coll.length; i++) {
coll[i].addEventListener("click", function () {
this.classList.toggle("active");
var content = this.nextElementSibling;
if (content.style.display === "block") {
content.style.display = "none";
} else {
content.style.display = "block";
}
});
}
function display() {
var x = document.getElementById("cover");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
</script>
You are attaching the onclick=display() to all of your list elements. GetElementById is going to return the first element with the given id, in this case it's always targeting your first cover (if you're triggering that elsewhere in your script). So since every 'read more' list element has the onclick function calling display(), it is always hitting your first element (because it's the first element with the respective id). What you could do instead pass in the event then use 'closest' and pass in the id there (if your intention is to hide the image as well). If not you can remove the display() on the onclick there.
The other elements are working as expected but you don't see it because your css on the enclosing container is hiding it (if you check your inspector you will notice the css being set as expected). You might want to add an overflow scroll to scroll within the container limits to see your expanded data, or use something like css flex with minimum height in order to expand the container to see your read more data

Append multiple images to divs using javascript only

I created a small script that counts images that I uploaded/inserted to my html source code. After I inserted images script creates div containers for those images. If I gave three images, then script will create three divs with class name etc. I have css rule with that class name. This was create before any images were in that container. Everything works but I just can't append those newly images to newly created divs. Is there a way using JavaScript only?
Here is a code:
if (document.getElementsByClassName("Multimedia")[0].getElementsByTagName("IMG")) {
total_number_of_images = document.getElementsByClassName("Multimedia")[0].getElementsByTagName("IMG").length;
for (i = 0; i < total_number_of_images; i = i + 1) {
document.getElementsByTagName("IMG")[i].className = "Image_clip";
child = document.getElementsByTagName("IMG")[i];
image_container = document.createElement("DIV");
image_container.className = "Image_container_div";
document.getElementsByClassName("Multimedia")[0].appendChild(image_container);
document.getElementsByTagName("IMG")[i].style.opacity = "0.8";
}
}
I tried somthenig like this:
image_container.appendChild(child);
But then I can get only two images into container... my third is out and also without className. Without this code, I get className for every image
You should cache the reference to elements rather than querying DOM in loops.
If I understood correctly, Your code should look something like the following for wrapping each image in a container <div>:
var container = document.getElementsByClassName("multimedia")[0];
// if there is only one match, use an id instead ------------^ ?
var images = container.getElementsByTagName("img");
for (var i = 0; i < images.length; i++) {
var img = images[i];
img.className = "imageClip";
img.style.opacity = "0.8"; // Why not define this in imageClip class ..?
imageContainer = document.createElement("div");
imageContainer.className = "imageContainer";
imageContainer.appendChild(img);
container.appendChild(imageContainer);
}
This I get on Yahoo answer. Posted by YaYox: http://jsfiddle.net/ffxad4bq/4
function myFunction() {
var multimedia = document.getElementsByClassName("Multimedia")[0]
var imgs = multimedia.getElementsByTagName("IMG");
for (var i = 0; i < imgs.length; i++) {
imgs[0].className = "Image_clip";
imgs[0].style.opacity = "0.3";
multimedia.innerHTML += '<div class="Image_container_div">'+imgs[0].outerHTML+'</div>';
imgs[0].remove()
}
}
I realized what was the problem. I shouldn't itaret through images. Just leave it on zero because, when loops start, code append one image at a time. When second loop starts I don't have any more 3 images, but two, that is why one image always stays out because loop goes three times.

Javascript Custom Alert Box with Image alignment

I Have created Custom Alert Box in Javascript . I Have added text with images. but It is not align proberly. It came some thing like this.
I am trying to add the correct mark and text with same line, how can I achieve this. can anyone please help me. I have added my Custom alert box Function below.
function createCustomAlert(txt, string_url,fd) {
// shortcut reference to the document object
d = document;
// if the modalContainer object already exists in the DOM, bail out.
if (d.getElementById("modalContainer")) return;
// create the modalContainer div as a child of the BODY element
mObj = d.getElementsByTagName("body")[0].appendChild(d.createElement("div"));
mObj.id = "modalContainer";
// make sure its as tall as it needs to be to overlay all the content on the page
mObj.style.height = document.documentElement.scrollHeight + "px";
// create the DIV that will be the alert
alertObj = mObj.appendChild(d.createElement("div"));
alertObj.id = "alertBox";
// MSIE doesnt treat position:fixed correctly, so this compensates for positioning the alert
if (d.all && !window.opera) alertObj.style.top = document.documentElement.scrollTop + "px";
// center the alert box
alertObj.style.left = (d.documentElement.scrollWidth - alertObj.offsetWidth) / 2 + "px";
// create an H1 element as the title bar
h1 = alertObj.appendChild(d.createElement("h1"));
h1.appendChild(d.createTextNode(ALERT_TITLE));
btn2 = alertObj.appendChild(d.createElement("img"));
btn2.id = "fd";
btn2.src = fd;
// create a paragraph element to contain the txt argument
msg = alertObj.appendChild(d.createElement("p"));
msg.innerHTML = txt;
// create an anchor element to use as the confirmation button.
//btn = alertObj.appendChild(d.createElement("a"));
//btn.id = "closeBtn";
//btn.appendChild(d.createTextNode(ALERT_BUTTON_TEXT));
//btn.href = "";
btn = alertObj.appendChild(d.createElement("img"));
btn.id = "closeBtn";
btn.src = 'new-go-next2.png';
btn.href="#ss";
//btn.height="30px";
//btn.width="30px";
//btn.href="#";
// set up the onclick event to remove the alert when the anchor is clicked
btn.onclick = function () { removeCustomAlert(); window.location = string_url; return false; }
}
well yes creating a table would be a great approach to solve your problems , btw u can also try some internal divs with proper position anf the element having correct float attribute
Rather creating div element create table with two Columns. First of which will contain 'Image' for OK and Second one will contain your 'Text'.
Check if this helps.

js - swap image on click

I'm trying to replace one div with another and turn the others off:
JS
function imgToSWF1() {
document.getElementById('movie-con2 movie-con3 movie-con4').style.display = 'none';
document.getElementById('movie-con').style.display = 'block';
}
function imgToSWF2() {
document.getElementById('movie-con movie-con3 movie-con4').style.display = 'none';
document.getElementById('movie-con2').style.display = 'block';
}
function imgToSWF3() {
document.getElementById('movie-con movie-con2 movie-con4').style.display = 'none';
document.getElementById('movie-con3').style.display = 'block';
}
function imgToSWF4() {
document.getElementById('movie-con movie-con2 movie-con3').style.display = 'none';
document.getElementById('movie-con4').style.display = 'block';
}
HTML
<span onmouseover="src=imgToSWF1();"><div class="numbers">01</div></span>
<span onmouseover="src=imgToSWF2();"><div class="numbers">02</div></span>
<span onmouseover="src=imgToSWF3();"><div class="numbers">03</div></span>
<span onmouseover="src=imgToSWF4();"><div class="numbers">04</div></span>
I can't seem to get this to work and I believe that targetting multiple ID's isn't possible like this? Anyway any advice would be smashing - thanks!
You're correct that you cannot supply multiple ids to document.getElementById(). Instead, you can grab them all individually using an array. There are many ways to accomplish what you are trying to do. This is a straightforward method based on iterating through the array of the elements to hide and hiding all of them.
This method expects you to define the array of nodes to hide in each of your functions, and so is non-ideal.
// Example:
function imgToSWF1() {
var nodes = ['movie-con2', 'movie-con3', 'movie-con4'];
// Loop over and hide every node in the array
for (var i=0; i<nodes.length; i++) {
document.getElementById(nodes[i]).style.display = 'none';
}
document.getElementById('movie-con').style.display = 'block';
}
Better:
This can be refactored into one function, however. Make one function which recieves the node you want to show as an argument. Hide the others. The array should contain all nodes that may be hidden in any circumstance, and be defined at a higher scope than the function.
// Array holds all nodes ids
var nodes = ['movie-con', 'movie-con2', 'movie-con3', 'movie-con4'];
// Function receives a node id which will be shown
function imageToSWF(nodeId) {
// Loop over and hide every node in the array
for (var i=0; i<nodes.length; i++) {
document.getElementById(nodes[i]).style.display = 'none';
}
// And unhide/show the one you want, passed as an argument
document.getElementById(nodeId).style.display = 'block';
}
Call as:
<span onmouseover="imageToSWF('movie-con');"><div class="numbers">01</div></span>
<span onmouseover="imageToSWF('movie-con2');"><div class="numbers">02</div></span>
<span onmouseover="imageToSWF('movie-con3');"><div class="numbers">03</div></span>
<span onmouseover="imageToSWF('movie-con4');"><div class="numbers">04</div></span>
You have to target one element at a time with document.getElementById, eg. document.getElementById('movie-con2').style.display='none'; document.getElementById('movie-con3').style.display='none';
etc, etc.
You could also use Jquery siblings selector to show or hide all elements that are siblings within a parent tag.
You definitely can't do that in straight up javascript. The document.getElementById function only returns a single element from the DOM.
Some docs can be had here:
http://www.w3schools.com/jsref/met_doc_getelementbyid.asp
https://developer.mozilla.org/en-US/docs/DOM/document.getElementById
If you were to use a toolkit like jQuery you could do something like:
$('div[id^="movie-con"]').hide(); // hide everything
$('div["movie-con"' + index + "]").show(); // show the one we want
Since you're not using jQuery it's not quite as easy. Something like:
var matches = document.getElementById("containerDiv").getElementsByTagName("img");
for( var i = 0; i < matches.length; i++ )
matches[i].style.display = "none";
document.getElementById('movie-con' + index).style.display = "block";

Categories

Resources