I have a webpage where i have 3 images and I have a button to hide those images all at once on click, and then show them(this part is not implemented yet). I have a JS function for hiding them but it is not working and I have no idea why. So this is part of my code:
<div id="left"><img id="leftimage" name="leftimage" src="pic1url.jpg" style=
"visibility:visible"></div>
<div id="centerright">
<div id="center"><img id="centerimage" name="centerimage" src="pic2url.jpg"
style="visibility:visible"></div>
<div id="right"><img id="rightimage" name="rightimage" src="pic2url.jpg"
style="visibility:visible"></div>
</div><script type="text/javascript">
var hideShowButton = document.getELementById("hideShowButton");
hideShowButton.onclick = function()
{
var allImages = { left:"leftimage"; center:"centerimage"; right:"rightimage"};
if(document.getElementById("leftimage").style.visibility == 'visible')
{
for ( var image in allImages)
{ document.getElementById(allImages[image]).style.visibility = 'hidden';
document.getElementById(allImages[image+"1"]).style.visibility = 'hidden';
document.getElementById(allImages[image+"2"]).style.visibility = 'hidden';
}
document.getElementById("hideShowButton").innerHTML = "Mostrar imagens";
}
}
</script>
<div id="buttons">
<input id="hideShowButton" type="button" value="Hide Pics">
</div>
Before reading the answer, I highly suggest you learn how to use the browser's console. It will print all the errors that make your JavaScript code to crash. I also suggest you take some time to read JavaScript tutorials :)
There are many things wrong with your code. First, there is a typo "getELementById" (L is uppercase instead of lowercase). Second, you need to place the script tags bellow your button. Third, when creating an object, you should separate it's properties using commas (,) not semicolons (;) . Finally, you made a false use of the for loop. Just to help you out, here is the corrected code but don't expect people to do that for you every time. You need to find mistakes like these on your own in the future :)
<div id="left">
<img src="pic1url.jpg" id="leftimage" style="visibility:visible" />
</div>
<div id="centerright">
<div id="center">
<img src="pic2url.jpg" id="centerimage" style="visibility:visible"/>
</div>
<div id="right">
<img src="pic2url.jpg" id="rightimage" style="visibility:visible"/>
</div>
</div>
<div id="buttons">
<input type="button" value="Hide Pics" id="hideShowButton" />
</div>
<script type="text/javascript">
var hideShowButton = document.getElementById("hideShowButton");
hideShowButton.onclick = function()
{
var allImages = { left:"leftimage", center:"centerimage", right:"rightimage"};
if(document.getElementById("leftimage").style.visibility == 'visible')
{
for ( var image in allImages)
{
document.getElementById(allImages[image]).style.visibility = 'hidden';
}
document.getElementById("hideShowButton").innerHTML = "Mostrar imagens";
}
}
</script>
Use can use diplay none or block property of css to hide and show any view respectively
<img id="one" src="pic1url.jpg" style="display:none;" />
Through javascript you can use this
document.getElementById(one).style.display = 'none';
Sorry, but your code is a bit messy. Why are you using a for statement if then you try to hide every image every time?
By the way, you're misusing the for...in statement. AllImages is a asociative array with no numeric indexes. for (var image in AllImages), image will be 'left', then 'center', then 'right' (the names of the properties of the object you're using). So a statement like
AllImages[image+1]
will return 'undefined' and your code will throw an error. Your code should look like this:
hideShowButton.onclick = function()
{
var allImages = { left:"leftimage"; center:"centerimage"; right:"rightimage"};
if(document.getElementById("leftimage").style.visibility == 'visible')
{
for ( var image in allImages)
{
document.getElementById(allImages[image]).style.visibility = 'hidden';
}
document.getElementById("hideShowButton").innerHTML = "Mostrar imagens";
}
}
By the way, I suggest you to read some documentation about loops in javascript, like MDN
Related
I have the following:
function changeFirst() {
let p = document.getElementById("firstElement")[0].innerhtml;
alert(p);
if (p = "<h1>This is the 1st element</h1>") {
document.getElementById("firstElement").innerHTML = "<h1>Changed first</h1>"
} else {
document.getElementById("firstElement").innerHTML = "<h1>Switched back first</h1>"
}
}
<div id="firstElement">
<h1>This is the 1st element</h1>
</div>
<button onclick="changeFirst()">Change first element</button>
I basically want the button to alternate the contents of the firstElement div. Why doesn't this work?
Thank you
document.getElementById returns ONE element
Also = is assignment, you want == or === for comparison
Could you possibly mean this:
function changeFirst() {
let h = document.querySelector("#firstElement h1");
h.textContent = h.textContent==="This is the 1st element" ? "Changed first" : "This is the 1st element"
}
<div id="firstElement">
<h1>This is the 1st element</h1>
</div>
<button type="button" onclick="changeFirst()">Change first element</button>
Here is exactly what you asked for. You were close.
1) when including javascript, you can just use script tags and it will work fine, when you use JSON or JQuery, that's when you have to use an include tag of a .js file. javascript code can be notated with script type = text/javascript.
2) when making a comparison in javascript: use three equal signs (===)
when making a non variable type-sensitive comparison: use two equal signs (==)
when setting a variable: use one equal sign (=)
https://www.geeksforgeeks.org/difference-between-and-operator-in-javascript/
3) When calling dynamic header, it is not an array, so you don't need [0], you are just comparing the innerhtml of the dynamic header div and it is only one header, arrays are for multiple things. Keep working on code, as you seem to have a good start, and made some minor syntax errors.
<!DOCTYPE html>
<html>
<body>
<button onclick="changeHeader()">Click me</button>
<div id="dynamicHeader"><h1>Hello World</h1></div>
<p>Clicking the button changes the header.</p>
<script>
function changeHeader() {
if (document.getElementById("dynamicHeader").innerHTML === "<h1>Hello World</h1>") {
document.getElementById("dynamicHeader").innerHTML = "<h1>Goodbye World</h1>";
} else {
document.getElementById("dynamicHeader").innerHTML = "<h1>Hello World</h1>"
}
}
</script>
</body>
</html>
Try like this. Here I introduced a flag and switched it to check content.
var changed = false;
function changeFirst() {
if (!changed) {
changed = true;
document.getElementById("firstElement").innerHTML = "<h1>Changed first</h1>";
} else {
changed = false;
document.getElementById("firstElement").innerHTML = "<h1>Switched back first</h1>";
}
}
<div id="firstElement">
<h1>This is the 1st element</h1>
</div>
<button onclick="changeFirst()">Change first element</button>
How do you concatenate a Javascript variable into the url of a HTML image source tag? I have tried .$ANSWER. "$ANSWER" and +$ANSWER+ and none of these are working.
Do I need to use getElementbyID?
I have a folder of images named cat.jpg, dog.jpg, etc and I have a javascript array of these animal names.
One of them is chosen as $ANSWER and I want to then display the image, using the variable $ANSWER.
I have scoured the internet for any example of how to do this but can't find any.
What I have below is my best guess of how to write it, but I get "Not found" in the console log. The picture are in the folder, as this was working in PHP before I rewrote this in Javascript.
<div>
<img id="ANSWER" src='pictures/animals/$ANSWER.jpg' width=80% height=auto >
</div>
<script>
document.getElementById("ANSWER").src='pictures/animals/$ANSWER.jpg';
</script>
Also, if there is an easy way to do this in JQuery, I would love to know.
This is easy enough to do with raw JavaScript; simply ensure that each of the 'string' components are wrapped in quotes, and then make use of the plus sign (+) to concatenate with your variable(s). Note that the variable(s) should not be in quotes; only the supporting string(s) should be.
For example, if you have the variable cat, and want to craft it in the the URL pictures/animals/cat.jpg, you would use 'pictures/animals/' + $ANSWER + '.jpg'.
Also note that your width and height values need to be wrapped in quotes as well, and the initial setting of src is irrelevant, as it is overwritten.
This can be seen in the following:
var $ANSWER = 'cat';
document.getElementById("ANSWER").src = 'pictures/animals/' + $ANSWER + '.jpg';
console.log(document.getElementById('ANSWER').src);
<div>
<img id="ANSWER" width="80%" height="auto">
</div>
For a jQuery-specific solution, you can use the attr() method, passing 'src' as the first parameter, and your combined URL as the second:
var $ANSWER = 'cat';
$("#ANSWER").attr('src', 'pictures/animals/' + $ANSWER + '.jpg');
console.log(document.getElementById('ANSWER').src);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<img id="ANSWER" width="80%" height="auto">
</div>
Hope this helps! :)
If $ANSWER is declared in PHP, the rendered HTML/JS won't know about it.
You'd need to do something like this:
<div>
<img id="ANSWER" src='pictures/animals/$ANSWER.jpg' width=80% height=auto >
</div>
<script>
document.getElementById("ANSWER").src='pictures/animals/<?php echo $ANSWER; ?>.jpg';
</script>
Note: I haven't used PHP in ages, so I may be wrong in the specifics of the PHP syntax. Hopefully, you'll get the idea, though.
If it's declared somewhere in the JS, you can concatenate it like some of the other answers here suggested:
<div>
<img id="ANSWER" src='pictures/animals/$ANSWER.jpg' width=80% height=auto >
</div>
<script>
document.getElementById("ANSWER").src='pictures/animals/' + $ANSWER + '.jpg';
</script>
Is this what you are looking for:
var el = document.getElementById("ANSWER");
var images = ['dog', 'cat', 'fish'];
var index = 0;
function setImage() {
var img = images[index];
el.src = `pictures/animals/${img}.jpg`;
index++;
if (index >= images.len) {
index = 0;
}
}
setImage(); // Get the first URL into the img tag
setInterval(setImage, 2000); // Change images every 2 seconds.
<div>
<img id="ANSWER" src="" width="80%" height="auto" />
</div>
Here it is with images online:
var el = document.getElementById("ANSWER");
var images = [
'https://cdn.rentcafe.com/dmslivecafe/UploadedImages/57ffbe5a-055d-43c1-98fa-8be16ba066ca.jpg',
'http://archer.gamebanana.com/img/ico/sprays/kitten2_render.png',
'https://is5-ssl.mzstatic.com/image/thumb/Purple118/v4/71/46/8d/71468d8f-f9f9-cc04-b346-04a8fef0e7f1/source/256x256bb.jpg'];
var index = 0;
function setImage() {
el.src = images[index];
index++;
if (index >= images.len) {
index = 0;
}
}
setImage(); // Get the first URL into the img tag
setInterval(setImage, 2000); // Change images every 2 seconds.
<div>
<img id="ANSWER" src="" width="80%" height="auto" />
</div>
I'm a newbie and starting to learn coding. I have a question regarding the famous "How many fingers am I holding up?" project. So instead of an alert message, I want the actual image of a finger with 1-5 and the message of either it is correct or not.
I think there are jquery codes.. but i don't want to jump to jquery and learn hardcore javascript first. I'm stuck with creating image Arrays and cannot manage to make the image come up.
Here's the code I have:
<body>
<p>How many fingers am I holding up?</p>
<p><input type="text" id="guess"> <button id="checkGuess">Guess!</button></p>
<div id="image"></div>
<div id="text"></div>
<script type="text/javascript">
var imgArray = new Array();
imgArray[1] = new Image();
imgArray[1].src="images/1.png";
imgArray[2] = new Image();
imgArray[2].src="images/2.png";
imgArray[3] = new Image();
imgArray[3].src="images/3.png";
imgArray[4] = new Image();
imgArray[4].src="images/4.png";
imgArray[5] = new Image();
imgArray[5].src="images/5.png";
document.getElementById("checkGuess").onclick = function() {
var randomNumber = Math.random();
randomNumber = randomNumber * 6;
randomNumber = Math.floor(randomNumber);
if (document.getElementById("guess").value == randomNumber) {
doument.getElementById("image").innerHTML = imgArray[num] + alert("Well done! You got it!");
} else {
alert("Nope! The number was " + randomNumber);
}
}
</script>
</body>
Thanks Guys! Appreciate your help!
Cheers!
Char
I think you can do something like this fiddle.
https://jsfiddle.net/6a4p2po4/5/
What I did was to make the imgArray an array of src of images, and updated the img src depending on the result.
I noticed while working you have some typos and unset variables.
For example, "doument" is misspelled, and "'num'" is not set.
doument.getElementById("image").innerHTML = imgArray[num] + alert("Well done! You got it!");
It might help to use Chrome or another browser to check the console (F12). It will definitely help you debug.
Using console.log() instead of alert() will make it show up as a log instead of a pop up window, so you can check the values that you stored on variables, i.e. console.log(randomNumber);
You're on the right track! Good job so far!
You said
So instead of an alert message, I want the actual image of a finger...
which leads me to think that we never want to call alert() and instead want to display an image and a message. Assuming I am correct in my supposition, here is some code...
<html>
<head>
<!-- some other stuff... -->
<!-- CSS is your friend! -->
<style>
.hidden {
display: none;
}
</style>
</head>
<body>
<p>How many fingers am I holding up?</p>
<p>
<input type="text" id="guess">
<button id="checkGuess" onclick="checkGuess()">Guess!</button>
</p>
<div id="image">
<!-- We can put the images in here then just hide/show them, which is much easier! -->
<img class="hidden" src="./images/1.png"/>
<img class="hidden" src="./images/2.png"/>
<img class="hidden" src="./images/3.png"/>
<img class="hidden" src="./images/4.png"/>
<img class="hidden" src="./images/5.png"/>
</div>
<div id="text"></div>
<script>
function checkGuess(){
var actualFingerCount = Math.floor(Math.random() * (5 - 1 + 1)) + 1;
//the `+` casts the value into a number
var userGuess = +document.getElementById('guess').value;
//get all of our images
var images = document.querySelectorAll('img');
//hide all of them just to be safe
images.forEach(function(img){
img.classList.add('hidden');
});
//then show the one we want
images[actualFingerCount - 1].classList.remove('hidden');
var textDiv = document.getElementById('text');
if(actualFingerCount === userGuess) {
textDiv.innerHTML = 'Yay, you got it!';
}
else {
textDiv.innerHTML = 'Whoops, try again! The number was ' + actualFingerCount + '.';
}
}
</script>
</body>
</html>
And there you have it!
Notice that this is a contrived example. In the real world, you should never define functions in the global namespace, nor should you rely on elements being in a certain order, like I did with the images. Maybe you can take it and improve it to follow better coding standards!
I need help regarding on how to determine a file type using JavaScript. For example in this html.
<div class="indi-download">
<div class="pull-left">
<h6 class="file-format">%file_display_name%</h6>
</div>
<div class="pull-right">
<a class="download-link" href="%file_url%">Download</a>
</div>
on this line of code,
<a class="download-link" href="%file_url%">Download</a>
the href="%file_url%" will return the file type with the following extensions:example: .docx or .pdf.
something like this.
<a class="download-link" href="http://mysite.com/download/myfiles/sample.pdf">Download</a>
my problem is, I need to detect what type of file is that using javascript. And if it is a .pdf, the class class="file-format" will change into class="pdf-file-format" and class="doc-file-format" for .doc. It depends on the file extension. Any idea on how to do this? what must be the best trick to do this?
This is my sample output, I just want to change the icon of a file that's why I need to change the class name.
EDIT
I did something like this but it doesn't work if there are multiple items on the list. Its only working on the first item. please help me.
<body onload="myFunction()">
<div class="indi-download">
<div class="pull-left">
<h6 class="pdf-file" id="file-display-id">%file_display_name%</h6>
</div>
<div class="pull-right">
<a class="download-link" id="download_link" href="%file_url%">Download</a>
</div>
</div>
</body>
JavaScript
<head>
<script type="text/javascript">
function myFunction()
{
var url = document.getElementById("download_link").href;
var ext = url.split('.').pop();
if(ext=='pdf'){
var newfileclass = document.getElementById("file-display-id");
newfileclass.className="pdf-file";
}
else if((ext=='docx')){
var newfileclass = document.getElementById("file-display-id");
newfileclass.className="pdf-file doc-file";
}
else if(ext=='zip'){
var newfileclass = document.getElementById("file-display-id");
newfileclass.className="pdf-file zip-file";
}
else{
var newfileclass = document.getElementById("file-display-id");
newfileclass.className="other-file";
}
}
</script>
</head>
If all your files have an extension just split the file name with extension = filename.split('.'); and the determine the file type by the extension.
How about this:
function changeClass(fileUrl){
var extension = fileUrl.split('.').pop();
if(extension.toLowerCase() == 'pdf')
{
return "pdf-file-format";
}
}
$(document).ready(function(){
$(a).live().addClass(changeClass( $(a).attr('href') ) );
});
It's sort of a pseudo code and I haven't tested it, but I think you get the point of what I have in mind ;)
Also as Lakshmi stated: How to get a extension of a file using jquery or javascript?
Does the class have to be "pdf-file-format"? I detect .pdf file links on my own site straight through CSS, like
a[href$="pdf"] { /* css styles for pdf links */ }
Eh?
Give an id to a tag
<a class="download-link" id="download_link" href="http://mysite.com/download/myfiles/sample.pdf">Download</a>
And use this javascript function to change the class
var change_class_a = function(url) {
var m = url.match(/(.*)[\/\\]([^\/\\]+)\.(\w+)$/);
if(m[3] == 'pdf')
document.getElementById("download_link").className = "YOUR_CLASS";
};
var url = document.getElementById("download_link").href;
change_class_a(url);
I know this is a silly question but i am not able to get the required result.I want to assign a javascript variable bck in document.getElementById(bck) .Everything is working fine i.e. alert displaying the correct value of variable bck but when i am using it inside the document.getElementbyID i am getting the following error:
document.getElementById(bck) is null
I googled it and looked in SO relevant topics also but got nothing helpful.
the value of backdropcontent[m][1] is Reden,also the value of selectedbg is Reden.
<script>
for ( var m=0;m<backdropcontent.length;m++) {
if(selectedbg==backdropcontent[m][1]){
var bck=backdropcontent[m][1]+'div1';
alert(bck);
document.getElementById(bck).style.display = "block";
document.getElementById(bck).style.top = "0px";
}
}
</script>
html part:
<div class="mcdropdown" id="Redendiv1" style="display:none;position:relative">
<a style="cursor: default !important">
<input type="text" name="reden1" id="reden1" style="background-image: url('<?php echo $mosConfig_live_site; ?>/templates/performitor/images/123.png');background-repeat: no-repeat;height:14px;width:130px !important;color:#BDBDBD;border: 1px solid #8e9daa;" disabled="disabled" value="Totaal" autocomplete="off"/>
</a>
</div>
please note that i dont want to alter the structure of my code so please dont suggest any major change.
Any help will be appreciated.Thanks.
The element with id backdropcontent[m][1]+'div1', does not exist
It's throwing error mostly because your element doesn't exist on the page yet. Move your <script> block below your code or use window.onload event.
window.onload = function(){
//your code
}
Or using jquery:
$(document).ready(function() {
// your code
});
you use the code in the following pattern
<script>
for ( var m=0;m<backdropcontent.length;m++) {
if(selectedbg==backdropcontent[m][1]){
var bck=backdropcontent[m][1]+'div1';
alert(bck);
document.getElementById("bck");.style.display = "block";
document.getElementById(bck).style.top = "0px";
}
}
</script>
May be this code helps you.