I'm still quite new to JavaScript so sorry for any incorrect terms etc.
I've got an image changer that uses buttons, and has the image stored within the button, but I know there's a way to compress these into an array and print out image by using 'image_array(0)' for example to get the image from the array.
Code below;
<!DOCTYPE html>
<html>
<body>
<img id="image" src="blank_light.jpg" style="width:100px">
<p></p>
<button onclick="document.getElementById('image').src='green_light.jpg'">Green</button>
<p></p>
<button onclick="document.getElementById('image').src='yellow_light.jpg'">Amber</button>
<p></p>
<button onclick="document.getElementById('image').src='red_and_yellow_light.jpg'">Red/Amber</button>
<p></p>
<button onclick="document.getElementById('image').src='red_light.jpg'">Red</button>
<p></p>
<button onclick="document.getElementById('image').src='blank_light.jpg'">Reset</button>
</body>
</html>
I looked for a good 20 minutes for a similar thread but couldn't find anything specific, and with a cheap understanding of JavaScript and HTML, everything I found was too vague for what I'm looking for.
Thanks in advance.
The image is not stored within the button, you are just changing the image source on click. If by compress you mean that the image will have less bytes, then you are wrong, an array does not do that. It just keeps information contiguously. The only advantage is you can handle more dynamic things and maybe be more organized.
var imageSources = ["green_light.jpg", "yellow_light.jpg", "red_and_yellow_ligh", "red_light.jpg", "blank_light.jpg"]
var buttons = document.getElementsByClassName("change-image")
for (let i = 0; i < buttons.length; i++) {
buttons[i].onclick = function () {
document.getElementById("image").src = imageSources[i]
}
}
<!DOCTYPE html>
<html>
<body>
<img id="image" src="blank_light.jpg" style="width:100px">
<p></p>
<button class = "change-image">Green</button>
<p></p>
<button class = "change-image">Amber</button>
<p></p>
<button class = "change-image">Red/Amber</button>
<p></p>
<button class = "change-image">Red</button>
<p></p>
<button class = "change-image">Reset</button>
</body>
</html>
If I understand you correctly, you need altering the source of images through keeping images in an array.
[].slice.call(document.querySelectorAll('button'), 0)
Above line is to access all buttons in the DOM.
Do something like this.
var images = ['green_light.jpg',
'yellow_light.jpg',
'red_and_yellow_light.jpg',
'red_light.jpg',
'blank_light.jpg'
];
var imageElement = document.getElementById('image');
[].slice.call(document.querySelectorAll('button'), 0).forEach(function(button, index){
button.addEventListener('click',function(e){
imageElement.src = images[index];
console.log("Image changed to: ", images[index]);
});
});
<html>
<body>
<img id="image" src="blank_light.jpg" style="width:100px">
<p></p>
<button>Green</button>
<p></p>
<button>Amber</button>
<p></p>
<button>Red/Amber</button>
<p></p>
<button>Red</button>
<p></p>
<button>Reset</button>
</body>
</html>
Related
I wrote a script to make an automatic slideshow, and i want it to stop when i onlick (or onmouseover) the image (or the content) but it not work for me. Someone please show me if there're any error in my code. Thank you!
This is my code:
var slideIndex =1;
showslides(slideIndex);
function plusslide(n){
showslides(slideIndex+=n);
};
function showslides(n){
var i;
var slides = document.getElementsByClassName("fade");
if (n>slides.length){ slideIndex=1};
if(n<1){slideIndex=slides.length};
for (i=0; i<slides.length; i++){
slides[i].style.display = "none";
}
slides[slideIndex-1].style.display = "block";
};
var interval=setInterval(function(){slideIndex+=1; showslides(slideIndex);},1000);
document.getElementsByClassName("fade").onclick=function(){stop()};
function stop(){
clearInterval(interval);
};
<body>
<div class="page">
<div class="container">
<div class="content">
<div class="fade">
<img src="#" />
<p>1/3</p>
</div>
<div class="fade">
<img src="#" />
<p>2/3</p>
</div>
<div class="fade">
<img src="#" />
<p>3/3</p>
</div>
<a class="prev" onclick="plusslide(-1)">❮</a>
<a class="next" onclick="plusslide(1)">❯</a>
</div>
</div>
</div>
<script type="text/javascript" src="slide.js"></script>
</body>
There's a small typo in your code. Replace getElementsbyClassName with getElementsByClassName.
You can catch errors like this in the future by using your browser's developer console, where it will tell you where's an error in your code and what type. Just search for Developer Tools, it will help you find and fix errors like this yourself.
Edit:
Oh yes, didn't see that one. There is indeed also an error in this line:
document.getElementsByClassName("fade").onclick=function(){stop()};
Here's the issue. getElementsByClassName does not return a DOM element, but rather an array of elements, since there are multiple elements with that class name. You'll have to loop through each one in order to access onclick on them, just like you did in your function above, like this:
var slides = document.getElementsByClassName("fade");
for (var i = 0; i < slides.length; i++) {
slides[i].onclick = stop;
}
Also, small sidenote: I shortened function(){stop()} to just stop in my answer. Since you only call that function without any arguments in onclick, you can just directly bind stop to onclick.
I'm new to javascript and can't figure out the best way to solve this problem.
I have a div called info.
I have dozens of videos, and am constantly adding new videos.
When I click a video, I want to update info.
So I was thinking I need a hidden div with the text, and getElementsByClassName for something like this:
<div class="video"><a href="./video1.mp4" target="videoplayer" onclick="showDescription()><div class="description"><p>description for video1</div>
<div class="video"><a href=./video2.mp4 target="videoplayer" onclick="showDescription()><div class="description"><p>description for video2</div>
<div class="video"><a href=./video3.mp4 target="videoplayer" onclick="showDescription()><div class="description"><p>description for video3</div>
and
function showDescription(){
var description = this.getElementsByClassName("description");
document.getElementById("info").innerHTML = description;
{
That doesn't work. Is using getElementsByClassName a good way to do this, or can anyone suggest another way?
Here's the actual html I'm using:
<div id="videoplayer">
<iframe name="VideoPlayer" width="80%" height="100%" src="http://www.youtube.com/embed/videoseries?list=PL5A2FB27789F71E63> </iframe>
</div>
<div id="info">
<p>Welcome</p>
</div>
<div class="thumb"><p>
<img src="http://discolemonade.com/roku/images/thumbs/MusicVideos/MV-ThumbSmallPlaylist.jpg">
Hours of music videos, refreshed often.
</p>
<div class="longinfodiv">
<p class="longinfo">this is the long version of the music video playlist info</p>
</div>
</div>
And the javascript:
function changeInfo() {
var longinfo = document.getElementsByClassName("longinfo");
document.getElementById("info").innerHTML = longinfo;
}
First structure your HTML file properly:
<div class="video">
Link
<div class="description">description for video1</div>
</div>
Then use the following script:
function showDescription(){
var video = this.parentNode;
var desc = video.children[1];
document.getElementById("info").innerHTML = desc.innerHTML;
}
I need some help here. Whit this page i want to create own link tags with a image. When you click your image, you'll go to that page you have choose. I think i'm almost done but it does not work! What have i done wrong?!
When I click the img element to open the new page, the image pops up..
<head>
<meta charset="utf-8">
<title>Min Startsida</title>
<script type="text/javascript">
function newLink() {
var myNewLink = document.getElementById("link");
localStorage.setItem(link, myNewLink.value)
};
function newIcon() {
var myNewIcon = document.getElementById("icon");
localStorage.setItem(icon, myNewIcon.value)
};
function varIcon() {
document.getElementById("image").src = localStorage.getItem(icon)
};
</script>
</head>
<body>
<form>
<h1>lägg till länk</h1><br />
<input type="text" id="link"><br />
<input type="text" id="icon"><br />
<button onClick="newLink(), newIcon()">lägg till länk</button>
</form>
<section>
<img src="#" id="image" onLoad="varIcon()">
</section>
</body>
This must be a string:
localStorage.setItem("link", myNewLink.value)
^^^^
what happens here is that the element is used as a key as link is used as an id - key has to be a string. This goes for both the setItem methods and the getItem as well that you use later:
<a href="#" onClick="location.href = localStorage.getItem('link')">
Alos, this must be separated with a semi-column:
<button onClick="newLink(); newIcon()">
^
(I didn't look further than these points)
I have some text inside <span></span> tags and I want to change that text to something else when page is loaded.
So lets say default text is 'Story' (outputted by some CMS system and I can't edit it). So when page is loaded, .js detects that 'Story' word and replaces it with 'View This Story'.
Is that possible somehow?
Cheers
Update: I did search before asking and none of those methods I found works. Like I said the text is outputted by CMS and it gives wrong title, the title itself cannot be edited via CMS because it is used for other terms and tagging which is correct, so I was looking for js workaround to rename it on page load.
And span has no ID and I cannot give it any ID, because like I said it works as designed by CMS.
<div class="views-row views-row-1 views-row-odd views-row-first active">
<div class="views-field views-field-name">
<span class="field-content">Story</span>
</div>
</div>
<div class="views-row views-row-2 views-row-even">
<div class="views-field views-field-name">
<span class="field-content">Second Story</span>
</div>
</div>
As you can see spans do not have IDs, but repeating classes only.
UPDATED as per OP request
You can replace any text within spans. You could even use regular expressions to make it more flexible, but let's leave this for now:
Native Javascript
var lookupSpanAndReplace = function(textFrom, textTo) {
var spans = document.getElementsByTagName('span');
for (i=0; i<spans.length; i++)
if (spans[i].innerHTML.indexOf(textFrom) >= 0)
spans[i].innerHTML = mySpan.innerHTML.replace(textFrom, textTo);
}
lookupSpanAndReplace("Story", "My New Text");
jQuery
var lookupSpanAndReplace = function(textFrom, textTo) {
$('span:contains(' + textFrom + ')').each(function(index, element) {
$(element).text($(element).text().replace(textFrom, textTo));
});
}
lookupSpanAndReplace("Story", "My New Text");
Try
$('#spanID').text("View This Story");
or if you want to replace a part of text
$('#spanID').text(function () {
return this.innerHTML.replace('Story', 'View This Story');
});
Give you span an ID and then run text([your new text]) on that node:
HTML
<span id="mySpan">Story</span>
jQuery
$('#mySpan').text("View This Story");
JSFiddle with jQuery
Or you can do it without jQuery:
document.getElementById("mySpan").innerHTML = "View This Story";
JSFiddle with plain 'ol Javascript
<script>
function changeSpan(){
var spans = document.getElementsByTagName ("span");
for (i = 0; i < spams.length; i++){
spans[i].innerHTML = textThatYouWant ();
}
}
</script>
<head onload="changeSpan()" >
<tile> ... </title>
</head>
<body>
...
</body>
Use the following to solve the issue.
HTML code:
<html>
<head>
<script>
function replace_text_span()
{
for(i=0;i<document.getElementsByTagName('span').length;i++)
{
document.getElementsByTagName('span')[i].innerHTML=document.getElementsByTagName('span')[i].innerHTML.replace("Story","View This Story");
}
}
</script>
<style>
</style>
</head>
<body onload="replace_text_span()">
<div class="views-row views-row-1 views-row-odd views-row-first active">
<div class="views-field views-field-name">
<span class="field-content">Story</span>
</div>
</div>
<div class="views-row views-row-2 views-row-even">
<div class="views-field views-field-name">
<span class="field-content">Second Story</span>
</div>
</div>
</body>
</html>
I need to know how to clone hard coded elements in runtime?
I have a hard coded input field. In run time is it possible to read that element and make it multiple(append) by user request. Is that possible with jquery or javascript.
Thanks in advance.
Using jQuery clone:
<div class="smallBox">
I'm a small box
<div class="smallInnerBox">I'm a small small inner box</div>
</div>
$('.smallBox').clone().insertAfter(".smallBox");
<div class="smallBox">
I'm a small box
<div class="smallInnerBox">I'm a small small inner box</div>
</div>
<div class="smallBox">
I'm a small box
<div class="smallInnerBox">I'm a small small inner box</div>
</div>
If you're looking for something a little more comprehensive:
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.4.4.js"></script>
</head>
<body>
<ul id='itemList'>
<li>
<input class='input' type="text" value="some text"/>
<a class='clone' href='Javascript:;'>Clone</a>
</li>
</ul>
<a id='allValues' href='Javascript:;'>Get Values</a>
<script>
$('a.clone').live('click', function() {
var clonedItem = $(this).parent().clone();
clonedItem.find('.input').attr('value', 'cloned');
$('#itemList').append(clonedItem);
});
$('#allValues').click(function(){
var values = [];
$('.input').each(function(i, text){
values[i] = $(text).val();
});
alert('Values are: ' + values.join(', '));
});
</script>
</body>
</html>
What do you mean by "hardcoded"? is this what you need?
$(document).ready(function () {
$("#something").click(function(){
$("#yourform").append($("#yourinputfield"))
});
})
<div id="divElement">Hello</div>
<button onclick="javascript:cloneElement()">Clone Me</button>
function cloneElement()
{
$("#divElement").clone().appendTo("#divElement");
}
Or: http://jsfiddle.net/UFcTk/