replace a image in html with using of java script - javascript

I don't understand what am I doing wrong here, I try to debug the code, but I did not found what I did wrong here.
I tried to replace the image in html with using of java script, I would appreciate some useful help for my problem
Html code:
<img id = "lamp" src = "js/Capture.PNG"/>
<!--make a button to turn on or off the lamp in this case -->
<button id = "off" name = "offf" onclick="change_attribute()" >Turn off the light</button>
<button id = "on" name = "offf" onclick="change_attribute()"> turn on the light </button>
Javacript code:
function change_attribute() {
var x = document.getElementsByName("offf");
if (x.id === "off")
{
document.getElementById('off').src = "js/Capture.PNG/";
}
else
{
document.getElementById('on').src = 'js/Capture2.PNG/'
}
}

The getElementsByName() method returns a collection of all elements in the document with the specified name. you are trying to reference an id property which doesn't exist in the array but on the actual array elements.
You should propbably refactor your code to use a single html element which calls the change_attribute() and it will toggle the state respectively between on and off.

getElementsByName() returns an array of HTML elements that specifies the given condition.
In your condition you are getting array of buttons html element as a result of which, when you are accessing x.id then it is giving error as x is array, rather than object.
try to refactor your code and call change_attribute from one place only

function change_attribute(e) {
if (e.target.id === "off")
{
document.getElementById('lamp').src = "https://cdn-icons-png.flaticon.com/512/2910/2910914.png";
}
else
{
document.getElementById('lamp').src = 'https://cdn-icons-png.flaticon.com/512/702/702797.png'
}
}
#lamp{
width: 50px;
height: 50px;
margin-right:15px;
}
<img id="lamp" src ="https://cdn-icons-png.flaticon.com/512/2910/2910914.png"/>
<!--make a button to turn on or off the lamp in this case -->
<button id="off" class="lightBtn" onclick="change_attribute(event)" >Turn off the light</button>
<button id="on" class="lightBtn" onclick="change_attribute(event)"> turn on the light </button>

Related

How to use 1 id for everything instead of 3 (for the following code)

I have the following html (it's a card) where a class is added to change the look of it:
<div class="card-small-half" id="card-1">
<a href="components/">
<div class="action-bar">
<p>Add Page</p>
<i class="material-icons">add</i>
</div>
</a>
</div>
and a switch made with a label that checks and unchecks an input type checkbox:
<div class="switch-wrapper" id="switch-wrapper-1">
<input type="checkbox" id="input-1" class="display-none">
<label class="switch" for="input-1"></label>
<p id="switch-caption-1">Visible</p>
</div>
With the following Javascript I add a class called "card-disabled" to the card:
window.onload = function () {
function check() {
if (document.getElementById("input-1").checked) {
document.getElementById("switch-caption-1").textContent = "Disabled";
$('#card-1').addClass('card-disabled');
} else {
document.getElementById("switch-caption-1").textContent = "Visible";
$('#card-1').removeClass('card-disabled');
}
}
document.getElementById('input-1').onchange = check;
check();
}
I know in css you can call id's or classes like so:
#switch-wrapper-1 input { /* styles */ }
or
#switch-wrapper-1 p { /* styles */ }
How can I do this with javascript, so I don't have to use an id for every element and instead use a global id for every wrapper.
EDIT:
The wrapper and input id's are unique! I want to call the paragraph inside the unique wrapper element something like this:
document.getElementById("switch-wrapper-1 p").textContent = "Disabled";
The 'p' here means paragraph
Is this possible and if so: how?
Query Selector is your friend here. You can use CSS selectors to retrieve DOM elements. In your case this call would return the first paragraph child in the #switch-wrapper-1 element.
var node = document.querySelector('#switch-wrapper-1 p');
If you also use jQuery, then as suggested in comments, you can simply use the $ function.
var $node = $('#switch-wrapper-1 p');
To select an individual element inside of an element with a specific ID using Javascript you can do:
document.getElementById('hello').getElementsByTagName('input')[0];
So in your example it would be:
document.getElementById('switch-wrapper-1').getElementsByTagName('input')[0].onchange = check;
The [0] is used because getElementsByTagName returns an array of all the child elements inside the parent element with the specified tag. Note that you will have to keep the unique ID on the input field if you want the for attribute on the label to function correctly.

How to get value of particular selector with same id?

How to get value of particular selector with same id?
function rev() {
var username = document.getElementById(value).value; /// or textContent;
return alert (username);
}
<button id="but" onclick="rev()">hey</button>
<button id="but" onclick="rev()">hey233</button>
But the reult always HEY
Any ideas?
You cannot have duplicate elements with the same ids. Its just not possible.
The id attribute for the elements must be unique. From the MDN :
The id global attribute defines a unique identifier (ID) which must be
unique in the whole document. Its purpose is to identify the element
when linking (using a fragment identifier), scripting, or styling
(with CSS).
Work Around:
You can use class or custom data-* attributes to get along with your logic. Read more about data-* attributes here
Hi you need seperate these, with the buttons having different ids
function rev1() {
var username = document.getElementById("but1").value; /// or textContent;
return alert (username);
}
function rev2() {
var username = document.getElementById("but2").value; /// or textContent;
return alert (username);
}
<button id="but1" onclick="rev1()">hey</button>
<button id="but2" onclick="rev2()">hey233</button>
As mentioned, Element id must be unique. But for what you are doing you do not need an id to get the text content of the button upon 'click', as the handler event knows the target element that was clicked.
function handler(event) {
alert(event.target.textContent);
}
var forEach = Function.call.bind(Array.prototype.forEach);
var buttons = document.querySelectorAll('button');
forEach(buttons, function(button) {
button.addEventListener('click', handler);
});
<button>hey</button>
<button>hey233</button>

How to change class name of two IDs at same time using js?

I have two IDs in same name ! if any one clicked among them , i need to change the class name of the both IDs. i know we should use ID for single use. Because of my situation(I have two classes for button ) so i have moved to ID.
Her is my code if i click one id that name only changes another one is remains same
<button class="success" id="1" onClick="reply(this.id)"> Added </button>
<button class="success" id="1" onClick="reply(this.id)"> Added </button>
js function
function reply(clicked_id)
{
document.getElementById(clicked_id).setAttribute('class', 'failed');
var el = document.getElementById(clicked_id);
if (el.firstChild.data == "Added")
{
el.firstChild.data = "Add";
}
}
if i use instead of 'class' to id while renaming class which one will be renamed success class or 'class name 1' ?
You can't. Getelementbyid will only return one element. Probably the first one.
Pure JS Is Second Example
My JS Fiddle Example: http://jsfiddle.net/eunzs7rz/
This example will use the class attribute only to perform the switching that you need, its a extremely basic example as do not want to go beyond what is needed... Also i forgot to remove the id's in the JS Fiddle Example.. so just ignore them
THE CSS:
.success {
background-color:#00f;
}
.failed {
background-color:#f00;
}
THE HTML:
<button class="success"> Added </button>
<button class="success"> Added </button>
THE JAVSCRIPT:
$(function() {
$(".success").click(function(){
Reply(this);
});
});
function Reply(oElm) {
$(oElm).attr('class', 'failed');
}
EDIT - PURE JAVASCRIPT VERSION
Sorry, did not think to check the post tags if this was pure JS. But here you go anyway ;)
<style>
.success {
background-color:#00f;
}
.failed {
background-color:#f00;
}
</style>
<button class="success" onclick="Reply(this)"> Added </button>
<button class="success" onclick="Reply(this)"> Added </button>
<script>
function Reply(oElm) {
oElm.className = 'failed';
}
</script>
THE MAIN THING HERE
Once you have the element either by using 'this' or by using 'getElementBy', you can then simply use ".className" to adjust the class attribute of the selected element.
As already explained by others, id is for single use and is quicker than using class or type. So even if you have a group, if only one is ever used.. use an id.
Then you use the object/reference of 'this' from an event on an element, in this case the onclick... that will send that variable to the function / code called.
So using 'this' is a preferred option as it will always reference the element that it is used/called from.
pass elemenet, not it's Id
<button class="success" id="1" onClick="reply(this)"> Added </button>
<button class="success" id="1" onClick="reply(this)"> Added </button>
function reply(elem)
{
$(elem).setAttribute('class', 'failed');
if (elem.firstChild.data == "Added")
{
elem.firstChild.data = "Add";
}
}
the ID attribute must be unique or else it will get the last defined element with that ID.
See this for reference.
Use a class instead of an id. ids are supposed to be unique in a dom tree.
html:
<button class="success" onClick="reply()"> Added </button>
<button class="success" onClick="reply()"> Added </button>
js:
var ary_success = document.querySelectorAll(".success"); // once and forever. If the set of elements changes, move into function `reply`
function reply () {
var elem;
var s_myclasses;
for (var i=0; i < ary_success.length; i++) {
elem = ary_success[i];
s_myclasses = elem.getAttribute('class');
s_myclasses = s_myclasses.replace ( /(success|failed)/g, '' );
s_myclasses = s_myclasses + ' failed';
elem.setAttribute('class', s_myclasses );
if ( elem.firstChild.data.indexOf("Added") !== -1) {
elem.firstChild.data = "Add";
}
}
}
Live Demo here.
Notes
Make sure that you set ary_successin the onload handler or in an appropriately placed script section - at the timeof execution the buttons must be present in the dom ! If in doubt, move it to the start of reply' body.
If you employ jquery, the code simplifies (well...) to:
$(document).ready( function () {
$(".success").on ( 'click', function ( eve ) {
$(".success").removeClass("success").addClass("failed");
$(".success *:first-child:contains('Added')").text(" Add ");
});
});
Updates
Notes, Live Demo
Iterator method changed, every not supported on test platform

Javascript function changeImage: Issues using variables for getElementById or getElementsByName

I'm having some trouble getting my code to do what I want. I have multiple sections that I have set to toggle show/hide, and it functions correctly. However, I'm now trying to switch the images to where instead of always being static with "More," I'd like it to switch to "Less" when it's expanded.
It does work... but only for the first one. If I press the buttons on any of the others, it only changes just the first one. You can see the page here:
http://jfaq.us
I've tried several different solutions with variables, but I can't seem to get it to work.
Help? Thanks in advance!
function changeImage() {
if (document.getElementById("moreorless").src == "http://jfaq.us/more.png")
{
document.getElementById("moreorless").src = "http://jfaq.us/less.png";
}
else
{
document.getElementById("moreorless").src = "http://jfaq.us/more.png";
}
}
function toggleMe(a){
var e=document.getElementById(a);
if(!e)return true;
if(e.style.display=="none")
{
e.style.display="block"
}
else{
e.style.display="none"
}
return true;
}
<div>
Guestbook
<div>
<input type="image" src="http://jfaq.us/more.png" id="moreorless" onclick="changeImage();return toggleMe('para3')" >
</div>
<div id="para3" style="display:none">
This is normally hidden, but shows up upon expanding.
This is normally hidden, but shows up upon expanding.
</div>
About
<div>
<input type="image" src="http://jfaq.us/more.png" id="moreorless" onclick="changeImage();return toggleMe('para2')" >
</div>
<div id="para2" style="display:none">
This is normally hidden, but shows up upon expanding.
This is normally hidden, but shows up upon expanding.
</div>
</div>
The id attribute must be unique. That's why it's not working. Also, it's not a good idea to use inline event handlers like you are doing, you should register event handlers using addEventListener instead.
Without changing all your code, one thing you can do is pass a reference to the currently clicked element to the changeImage function.
function changeImage(el) {
var moreUrl = 'http://jfaq.us/more.png';
el.src = el.src === moreUrl? 'http://jfaq.us/less.png' : moreUrl;
}
Then change the inline handler for onclick="changeImage(this);"
You are using same Id for all inputs. This is causing the problem.
Give every element a unique Id.
If you want to perform grp operation use jquery class.
That's because you use the same id for the both images, and getElementById apparently takes the first one.
Here is the updated code:
html:
<input type="image" src="http://jfaq.us/more.png" id="moreorless" onclick="changeImage.call(this);return toggleMe('para3')" >
script:
// inside the event handler 'this' refers to the element clicked
function changeImage() {
if (this.src == "http://jfaq.us/more.png") {
this.src = "http://jfaq.us/less.png";
} else {
this.src = "http://jfaq.us/more.png";
}
}
check this
http://jsfiddle.net/Asb5A/3/
function changeImage(ele) {
if (ele.src == "http://jfaq.us/more.png")
{
ele.src = "http://jfaq.us/less.png";
}
else
{
ele.src = "http://jfaq.us/more.png";
}
}
<input type="image" src="http://jfaq.us/more.png" onclick="changeImage(this);return toggleMe('para3')" >

Get numerical value from parent with id like 'post-1' and use it in jQuery function

I'm trying to figure out the following.
I have following jQuery code:
var as = "";
var bPlay = 0;
audiojs.events.ready(function() {
as = audiojs.createAll();
$(".audiojs .play-pause").click(function() {
var e = $(this).parents(".audiojs").index(".audiojs");
$.each(as, function(t, n) {
if (t != e && as[t].playing) {
as[t].pause()
}
})
bPlay = !bPlay;
if (bPlay == 1) {
$(".bar").each(function(i) {
fluctuate($(this));
});
} else {
$(".bar").stop();
}
})
});
In a nutshell it preforms list of things when someone clicks particular .audiojs instance on a page. 1) checks if there is any other instance playing, if there is pauses it. And if it is playing applies fluctuate function to elements on a page that have class="bar". This is the issue! I don't want to apply it to all .bar's on a page, but only to a specific group that is associated with particular .audiojs instance (the one that is being clicked and is playing).
I thought of the following solution. Each .audiojs instance is inside a div tag that has id like "post-1", "post-2" etc.. where numerical value is post id from database. I can add this numerical id to bar, so it would be like bar-1, bar-2 etc... However after this I'm having issues.
For javascript to work I need to retrieve numerical value from "post-[id]" associated with audiojs instance that is being clicked and than store it somehow, so I can use it like this afterwards
bPlay = !bPlay;
if (bPlay == 1) {
$(".bar-[value retrieved from post-...]").each(function(i) {
fluctuate($(this));
});
} else {
$(".bar-[value retrieved from post...]").stop();
}
Could someone explain to me how it can be achieved?
Honestly, the easiest way would be to stick it in a custom data-* attribute on the <div id="post-X"> element, like so:
<div id="post-1" data-bar="bar-1">...</div>
Then, you said your .audiojs element is inside that <div>, so just go from this inside the event handler to that <div> element (using .closest()) and get the value of it:
var barId = $(this).closest('[id^="post-"]').attr('data-bar');
Then when you need to use it:
$("." + barId).each(function(i) {
fluctuate($(this));
});
Instead of embedding the value in a class or ID, use a data-* attribute:
<div class="audiojs" data-fluctuate-target="bar-1">
<button type="button" class="play-pause">
<!-- ... -->
</button>
</div>
<div class="bar-1">
<!-- ... -->
</div>
In your click event handler, use the following to fluctuate or stop the correct elements:
var fluctuateClass = $(this).closest('.audiojs').attr('data-fluctuate-target');
$('.' + fluctuateClass).each(function () {
if (bPlay == 1) {
fluctuate($(this));
} else {
$(this).stop();
}
});

Categories

Resources