This question already has answers here:
Get global variable dynamically by name string in JavaScript
(6 answers)
Closed 5 years ago.
HTML:
<button id="s01" onclick="getMusic(this.id)"></button>
<button id="s02" onclick="getMusic(this.id)"></button>
JAVASCRIPT:
var s01 = ["file", "song"];
var s02 = ["file", "song"];
function getMusic(e){
alert()
}
Alright so I have this code above (This is a simplified version). This function will set e in getMusic(e) to either s01 or s02. I need to be able to call the variable that corresponds to that name (within the alert()) but I'm not even sure where to start. Any help is appreciated, thanks!
P.S. any chance I can remove the onclick="" from the HTML file and replace it with an addEventListener in the js file and still achieve the same effect? I don't like mixing my scripts like that.
If you use an object to hold your data, it's a lot easier
var data = {
s01 : ["file", "song"],
s02 : ["file", "song"]
};
function getMusic(e){
console.log( data[e] );
}
If you use addEventListener you can remove the inline javascript as well
var data = {
s01 : ["file1", "song"],
s02 :["file2", "song"]
}
document.querySelectorAll('.btn').forEach(function(el) {
el.addEventListener('click', function() {
console.log( data[this.id] );
});
});
<button id="s01" class="btn">Test 1</button>
<button id="s02" class="btn">Test 1</button>
First off, to answer your second question, yes, you can register the event listener in your JS:
document.querySelectorAll("input[type=button]").forEach(function(el){
el.addEventListener("click", getMusic)
})
Once you have your event handler registered that way, you can get the id of the button by accessing e.target.id.
function getMusic(e){
alert(e.target.id) // will alert with button id
}
At this point, you have a string containing the id; now you need to be able to pull the values that correspond to the id. It makes the most sense to defined a JSON bag with hashes corresponding to id.
var data = {
s01: ["your", "data"],
s02: ["your", "other", "data"]
}
function getMusic(e){
myData = data[e.target.id]
alert(myData)
}
In JavaScript, the window object exists, which contains all global variables.
Simply use window[e] to get your array's value:
var s01 = ["file", "song"];
var s02 = ["file", "song"];
function getMusic(e){
alert(window[e])
}
<button id="s01" onclick="getMusic(this.id)"></button>
<button id="s02" onclick="getMusic(this.id)"></button>
Related
I would like to change my icon from expand_more to expand_less in following code
<li class="dropdown-bt" onclick="dropdown('content');">
<a>dropdown-content <i class="material-icons">expand_more</i></a>
</li>
I am going to use same code multiple times so it would be better to using function multiple times. I thought of using ID for every piece of code but it would be to hectic. So I want to write single function do it but I don't know how, so please help.
Just pass an object event as a parameter, say e to your dropdown() and use the textContent property to retrieve the current element content, check it's value and replace the content with another text content like this:
var btn = document.getElementById("dropdownBt");
function dropdown(e) {
var innerText = e.target.children[0];
if(innerText.textContent == "expand_more") {
innerText.textContent = "expand_less";
} else {
innerText.textContent = "expand_more";
}
}
btn.addEventListener('click', dropdown);
<li class="dropdown-bt" id="dropdownBt"><a>dropdown-content <i class="material-icons">expand_more</i></a></li>
This question already has answers here:
get wrong value in data attribute jquery
(4 answers)
Closed 5 years ago.
I want change repeatedly the attribute value of data-number="2" when .next is clicked. It works at the first attempt that means the browser gives data-number value as 3. But when I click next times, it doesn't change. It remains 3.
Here my code:
<a class="prev" data-number="1">❮</a>
<a class="next" data-number="2">❯</a>
</div>
<script>
$(document).ready( function(){
$('a.next').on( 'click', function(){
var image_num = parseInt($(this).data('number')) + 1 ;
var num_to_string = image_num.toString();
var prev_value = $(this).attr("data-number", num_to_string );
console.log(prev_value);
} );
} );
</script>
I want to have the value as 3, 4, 5 ....
You didn't update the intended data-number-attribute, because you have to use data as well to update it. So I replaced this line:
$(this).attr("data-number", num_to_string )
with this line:
$(this).data("number", num_to_string);
$(document).ready(function () {
$('a.next').on('click', function () {
var image_num = parseInt($(this).data('number')) + 1;
var num_to_string = image_num.toString();
var prev_value = $(this).data('number', +num_to_string);
console.log(num_to_string);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a class="prev" data-number="1">❮</a>
<a class="next" data-number="2">❯</a>
</div>
The reason for this behaviour is that jquery handles data-attribute (data-number) differently than ordinary attributes like id because when dealing with data-attributes the DOM-element is actually not altered unlike with ordinary attributes, as this link states.
That's why both methods data and attr work different and can therefore not be used in combination as they are used in the question, because attr works with updated DOM-values but data does not.
Hope this helps.
If you use data() jQuery will automatically cast numeric data attribute values to number
$('a.next').on('click', function() {
var $el = $(this);
// increment the data object value of number property
$el.data().number ++;
console.log('New number:', $el.data('number'))
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Next
I've spent the past couple hours googling and browsing W3Schools and couldn't find a way to do exactly what I wanted. I've found similar articles but they don't answer my question perfectly.
So what I'm trying to do is this, create a JS function that when called in HTML will take the information given to return the appropriate information. E.G, I want there to be two HTML buttons. If the user presses the first button, it calls the function "onclick='show(x, y)'" and x and y which stand for another paragraph and an image. If the user presses the second button, it calls the same function with different variables "onclick='show(x, z)'" which would display the same paragraph as the other button would but would display a different image.
Basically, is it possible for HTML elements to have IDs that can be variable in JS so I that I do not have to create an individual JS function for every single button?
My Javascript:
<script>
var Show = function(elID, elID2) {
var el1 = document.getElementByID(elID);
var el2 = document.getElementByID(elID2);
var both = (elID) + " " + (elID2);
document.getElementById(elID).innerHTML = both;
}
</script>
My HTML:
<p id="demo">
<button onclick="Show(77, demo)">Click to convert</button>
</p>
I am still learning the ins and outs of Javascript so any and all help would be appreciated.
yes, enclose the arguments in quotes
<button onclick="Show('77', 'demo')">Click to convert</button>
without quotes 77 will be passed correctly but demo will not be since it will look for a demo property in window scope.
You should get innerHTML before inserting. Also note that, you must pass id attributes wrapped in quotes(').
ID attributes should at least have one character and it should not start with NUMBER
function Show(elID, elID2) {
var el1 = document.getElementByID(elID).innerHTML;
var el2 = document.getElementByID(elID2).innerHTML;
var both = (elID) + " " + (elID2);
document.getElementById(elID).innerHTML = both;
}
<p id="demo">
<button onclick="Show('77', 'demo')">Click to convert</button>
</p>
You could lay aside the inline JavaScript and opt for a different way, separating your markup from your logic.
https://jsfiddle.net/tricon/p2esv818/
HTML:
<button id="button" data-parameter-one='{ "keyOne": "valueOne", "keyTwo": "valueTwo" }'>
Some button
</button>
JavaScript:
var button = document.getElementById("button");
button.addEventListener("click", function() {
var parameters = this.getAttribute("data-parameter-one");
parameters = JSON.parse(parameters);
console.log(parameters);
});
I'm trying to change the text of the button without editing the HTML code but it doesn't really work
Here is the code:
document.querySelector(".game-button").onClick = function knop(knop) {
document.querySelector(".game-button").innerHTML = "Reset spel";
}
HTML:
<button class="game-button">Start spel</button>
If I may suggest:
var gameButton = document.querySelector(".game-button")
gameButton.onclick = function() {
gameButton.innerHTML = "Reset spel";
}
I've put the gamebutton in a variable so it is only referenced once.
Since this is a function connected to an onclick event, naming the function is not needed. Also, you are not passing or using any arguments, so there is no need to put anything between the ().
try this code
document.querySelector(".game-button").onClick = function knop() {
this.innerHTML = "Reset spel";
}
I have several fish images, within links, which are listed like so...
<img src="img/fish1.png" id="fish1"/>
<img src="img/fish2.png" id="fish2"/>
I want to take id 'fish1', 'fish2', ect. (based on which is clicked), and use a variable to replace some text.
The name of the variables are...
var fish1Hunger
var fish2Hunger
And the function I want to call with a variable is...
$(function() {
$('a.trigger').click(function() {
$('#popUp h3').html(REPLACE WITH VARIABLE ASSOCIATED WITH THE FISH);
});
});
How can I call the variable associated with the IMG id?
window[e.srcElement.id+"Hunger"];
Put that inside your click event with e being the event (function (e){...) and it should access the variable as long as it is in the global scope.
jsBin demo
var fish1Hunger = "Fish 1 is hunger!! Feed him!"
var fish2Hunger = "Fish 2 is hunger!! Feed him!"
$('a.trigger').click(function (e) {
e.preventDefault();
var ImLookingFor = $(this).find('img').attr('id')+'Hunger';
$('#popUp h3').html(eval(ImLookingFor));
});