Why its Choosing similar images? - javascript

i was trying to make a facemash like site using js. But when i click on an image is not changing the images rightly. its sometime showing same images in both the img elements. here the js code i use for selecting images when clicked.
function changeEle(id) {
var otherSrc = id == 0? imageElements[1].src : imageElements[0].src;
var ele = imageElements[id];
var oldSrc = ele.src;
var newSrc = randomFromArray(imagesList);
while(newSrc == oldSrc || newSrc == otherSrc) {
newSrc = randomFromArray(imagesList);
}
ele.src = newSrc;
}
imageElements[0].onclick = function() {
changeEle(1);
}
imageElements[1].onclick = function() {
changeEle(0);
}

Check what oldSrc and otherSrc contain with a debugger or console.log(). I think you'll find that the values aren't exactly the same as the original values in imagesList, so that when you do the comparison (newSrc == oldSrc || newSrc == otherSrc) images that are the same image as far as you're concerned manage to slip by.

Related

How to display paragraphs and images from div in order?

I am building a small web-tool where editors can write content by using buttons to add paragraphs and images. I store the elements with an id ((number of element) starting at 0 and incremented for every new element) and load with a button in order to a div "preview" where the content is supposed to be displayed as in the web page later on.
My issue is that, for a reason I don't understand, the image is always displayed below all the paragraphs instead of being in order. Presumably there is an easy fix, but I am very new to HTML, CSS and JS and couldn't find the solution online.
Sorry if this is a stupid mistake or the solution was already posted somewhere.
Javascript handling the preview rendering:
// Preview current document status
document.getElementById("previewButton").addEventListener("click", function() {
// Clear
document.getElementById("preview").innerHTML = "";
// Add all elements properly
var section = document.getElementById("preview");
var id = "preview";
for (var counter = 0; counter < element_counter; counter++) {
var type = document.getElementById(counter).nodeName;
// If text element
if (type === "TEXTAREA") {
var paragraph = document.createElement("p");
var text = document.getElementById(counter).value;
paragraph.setAttribute("id", id + counter);
paragraph.setAttribute("class", "flow-text");
paragraph.append(text);
section.appendChild(paragraph);
}
// If image element
if (type === "INPUT") {
var file = document.getElementById(counter).files[0];
var reader = new FileReader();
reader.onload = function(e) {
var image = document.createElement("img");
image.setAttribute("id", id + counter);
image.setAttribute("src", e.target.result);
image.setAttribute("class", "materialboxed responsive-img");
section.appendChild(image);
}
reader.readAsDataURL(file);
}
}
});
This might work. I can't test though without your code. However basically the principle at work is to isolate some of the vars so they represent distinct instantiations. And then immediately add the image element to the DOM. The reader.onload is expected to run asynchronously still.
enter code here if (type === "INPUT") {
(function() {
var file = document.getElementById(counter).files[0];
var reader = new FileReader();
var image = document.createElement("img");
image.setAttribute("id", id + counter);
image.setAttribute("class", "materialboxed responsive-img");
section.appendChild(image);
reader.onload = function(e) {
image.setAttribute("src", e.target.result);
}
reader.readAsDataURL(file);
}());
}

Attempting to change an image onclick via PHP/Javascript/HTML

I've looked at numerous other answers regarding this but haven't found a solution that has worked. I'm using a PHP page that contains some HTML code, with Javascript working some functions. Ideally I would select an image on the page, the image will become colored green as it is selected. I would then like to deselect the image and have it return to the original state. I can only get half-way there however. What am I missing? Is it something with post back?
Here's some code examples:
The HTML:<div onclick="changeImage(1)" id="toolDiv1"><img id="imgCh1" src="/images/Tooling/1.png"></div>
The Javascript function:
function changeImage(var i){
var img = document.getElementById("imgCh" + i + ".png");
if (img.src === "images/Tooling/" + i + ".png"){
img.src = "images/Tooling/" + i + "c.png";
}
else
{
img.src = "images/Tooling/" + i + ".png";
}
}`
The "1c.png" image is the one that is selected and should replace "1.png". There are multiple divs on this page that hold multiple images, which are named 2/2c, 3/3c, which is why the var i is included. Any insight? Thanks in advance.
You could do it something like this, it would also allow for different file names.
<img class="selectable" src="/images/Tooling/1.png"
data-original-source="/images/Tooling/1.png"
data-selected-source="/images/Tooling/1c.png">
<img class="selectable" src="/images/Tooling/2.png"
data-original-source="/images/Tooling/2.png"
data-selected-source="/images/Tooling/2c.png">
 
var images = document.getElementsByClassName('selectable');
for (var image of images) {
image.addEventListener('click', selectElementHandler);
}
function selectElementHandler(event) {
var image = event.target,
currentSrc = image.getAttribute('src'),
originalSrc = image.getAttribute('data-original-source'),
selectedSrc = image.getAttribute('data-selected-source'),
newSrc = currentSrc === originalSrc ? selectedSrc : originalSrc;
image.setAttribute('src', newSrc);
}
 
With comments:
// find all images with class "selectable"
var images = document.getElementsByClassName('selectable');
// add an event listener to each image that on click runs the "selectElementHandler" function
for (var image of images) {
image.addEventListener('click', selectElementHandler);
}
// the handler receives the event from the listener
function selectElementHandler(event) {
// the event contains lots of data, but we're only interested in which element was clicked (event.target)
var image = event.target,
currentSrc = image.getAttribute('src'),
originalSrc = image.getAttribute('data-original-source'),
selectedSrc = image.getAttribute('data-selected-source'),
// if the current src is the original one, set to selected
// if not we assume the current src is the selected one
// and we reset it to the original src
newSrc = currentSrc === originalSrc ? selectedSrc : originalSrc;
// actually set the new src for the image
image.setAttribute('src', newSrc);
}
Your problem is that javascript is returning the full path of the src (you can try alert(img.src); to verify this).
You could look up how to parse a file path to get the file name in javascript, if you want the most robust solution.
However, if you're sure that all your images will end in 'c.png', you could check for those last 5 characters, using a substring of the last 5 characters:
function changeImage(var i){
var img = document.getElementById("imgCh" + i);
if (img.src.substring(img.src.length - 5) === "c.png"){
img.src = "images/Tooling/" + i + ".png";
}
else
{
img.src = "images/Tooling/" + i + "c.png";
}
}

How to assign Javascript Image object to existing Img element of JSP

JSP code is written as below,
< img src='<%=imageURL%>' id='advt-image-top' border='0' alt=''" /><br/>
Where the value of imageURL is like,
http://1.2.3.4:5678/ads/avw.php?zoneid=1234567890&cb=INSERT_RANDOM_NUMBER_HERE
(Sample URL which fetches random advertisement image from Ad-Server)
Now, same JSP page contains javascript-code like below:
$(document).ready(function() {
var imgAd = new Image();
imgAd.src = '<%=imageURL%>';
imgAd.onload = function(){
if((this.width == 1 && this.height == 1)){
document.getElementById('advt-image-top').src='img/default_top.jpg';
}
}
}
Above javascript code checks - if image returned from ad-server is of size 1x1, then it should be replaced with default-image.
Problem is, above entire code-snippet executes "imageURL" twice in order to fetch one image from ad-server : one to check whether image-returned-from-ad-server is of size 1x1 and other during tag execution.
How can I optimize above code so that "imageURL" is executed only once?
How can I assign Image() object of javascript (after 1x1 validation is passed) to JSP's 'advt-image-top' element?
Thanks in advance.
You just need a minor adjustment to your javascript code, there is no need to create an Image:
$(document).ready(function() {
var imgAd = document.getElementById('advt-image-top');
imgAd.onload = function(){
if((this.width == 1 && this.height == 1)){
imgAd.src='img/default_top.jpg';
}
}
}
However, the image might get loaded before the document ready fires and lose the onload event, so you might want to load the default url in your tag:
< img src='img/default_top.jpg' id='advt-image-top' border='0' alt=''" /><br/>
...and apply the remote url by code:
$(document).ready(function() {
var imgAd = document.getElementById('advt-image-top');
imgAd.onload = function(){
if((this.width == 1 && this.height == 1)){
imgAd.src='img/default_top.jpg';
}
}
imgAd.src='<%=imageURL%>';
}
EDIT: probably the best way is to remove the img tag altogether from the jsp and write everything with javascript. Supposing that the image is contained in an element with id "container":
$(document).ready(function() {
var imgAd = new Image();
imgAd.onload = function(){
if((this.width == 1 && this.height == 1)){
imgAd.src='img/default_top.jpg';
}
}
imgAd.src='<%=imageURL%>';
imgAd.id='adv-image-top';
imgAd.border=0;
document.getElementById('container').appendChild(imgAd);
}
#dipanda, Thanks for your comments. Helped me solve my problem.
var $imgObj = $("<img/>",{src:"<%=imageURL%>"});
$imgObj.load(function(){
var imgJS = $imgObj[0];
if(imgJS.height == 1 && imgJS.width == 1){
document.getElementById('advt-image-top').src='img/default_top.jpg';
}else{
if($("#advt-image-top")!=null && $("#advt-image-top")!=undefined){
$("container").append($imgObj);
}
}
};

Javascript slideshow with caption issues

So I am having issues with captioning my slide show using a javascript, can somebody let me know as to where I am going wrong. My code stands as this:
JavaScript Document
var index = 0;
var titles=[1,2,3,4,5];
var img = document.getElementById("img1");
function moveToNextSlide()
{
if (index >= 5){index = 0}
var img = document.getElementById("img1");
var slideName = "movieImages/img" + titles[index++] + ".jpg";
img.src=slideName;
CaptionSlide();
}
function CaptionSlide()
{
if( img.attr("src") == "movieImages/img1.jpg")
document.getElementById("captionbar").innerHTML="Up!";
else if(img.attr("src") == "movieImages/img2.jpg")
document.getElementById("captionbar").innerHTML="Monsters Inc";
else if(img.attr("src") == "movieImages/img3.jpg")
document.getElementById("captionbar").innerHTML="Madagascar";
else if(img.attr("src") == "movieImages/img4.jpg")
document.getElementById("captionbar").innerHTML="Finding Nemo";
else if(img.attr("src") == "movieImages/img5.jpg")
document.getElementById("captionbar").innerHTML="Ice Age";
}
HTML document
<div class="slides">
<img id="img1" src="">
</div>
<input type="image" src="images/Next.png" id="button" onClick="javascript:moveToNextSlide()" title="Next" >
<div id ="captionbar"></div>
Also to note, that I get this error within the "inspect element":
Uncaught TypeError: Cannot call method 'attr' of null
REVISED
var index = 0;
var titles=[1,2,3,4,5];
var img = document.getElementById("img1");
function moveToNextSlide()
{
if (index >= 5){index = 0}
img = document.getElementById("img1");
var slideName = "movieImages/img" + titles[index++] + ".jpg";
img.src=slideName;
CaptionSlide();
}
function CaptionSlide()
{
window.onload = function(){
if( img.src === "movieImages/img1.jpg")
document.getElementById("captionbar").innerHTML="Up!";
else if(img.src === "movieImages/img2.jpg")
document.getElementById("captionbar").innerHTML="Monsters Inc";
else if(img.src === "movieImages/img3.jpg")
document.getElementById("captionbar").innerHTML="Madagascar";
else if(img.src === "movieImages/img4.jpg")
document.getElementById("captionbar").innerHTML="Finding Nemo";
else if(img.src === "movieImages/img5.jpg")
document.getElementById("captionbar").innerHTML="Ice Age";
}
}
The HTML Remains the same as before.
No error references however function does not write the text whatsoever.
Replace all img.attr('src') by img.src=="your image name".
For example:
img.src=="movieImages/img1.jpg"
As you are using pure JavaScript,you cannot use attr() which is method of JQuery.
attr() is a method brought by JQuery. If you are not using JQuery, you should keep using img.src. Another thing I noticed that might cause trouble : when you read .src from your image, you get the full path as a return (including your domain).
Your conditions would then become :
img.src === "http://yourdomain.com/movieImages/img1.jpg"
( And I just checked to be sure : http://www.w3schools.com/jsref/prop_img_src.asp mentions that the return value of img.src includes protocol and domain )
Also I think you should either define your function CaptionSlide inside moveToNextSlide so that it gains access to the updated img variable or not declare your img variable inside the moveToNextSlide function (so that the global variable gets updated instead)
Another point : you should make sure the DOM is loaded before querying elements from it (such as img) . To do so, wrap your code in a function, and assign it to the window.onload event :
window.onload = function() {
var index = 0;
var titles=[1,2,3,4,5];
var img = document.getElementById("img1");
function moveToNextSlide()
{
...
}
function CaptionSlide()
{
if( ... )
...
}
document.getElementById("button").addEventListener('click', moveToNextSlide);
}
and HTML for button :
<input type="image" src="images/Next.png" id="button" title="Next" />

Changing image with javascript

I'm using jquery mobile to make an app. I'm playing a sound file when the page loads and displaying an image to turn the sound file off when clicked. everything is working fine however I can only get the image to change on the index page. I can turn off the sound file on any page however the image wont change on any other page. please help =) <3
<script type="text/javascript">
var newsrc = "soundOff.png";
function changeImage() {
var sample = document.getElementById("foobar");
sample.pause();
if ( newsrc == "soundOff.png" ) {
document.images["sound"].src = "/img/soundOff.png";
document.images["sound"].alt = "Sound Off";
newsrc = "soundOn.png";
}
else {
var sample = document.getElementById("foobar");
sample.play();
document.images["sound"].src = "/img/soundOn.png";
document.images["sound"].alt = "Sound On";
newsrc = "soundOff.png";
}
}
var sample = document.getElementById("foobar");
sample.play();
document.images["sound"].src = "/img/soundOff.png";
Should be this:
document.getElementById('your_id').src = "/img/soundOff.png";
Your path seems a little wierd to me.Check it properly

Categories

Resources