Note: this is my first project, sorry if this is obvious, I've looked everywhere and can't find it
I'm working on a website that would serve as a better UI then file explorer/VLC, so I've made a button where you can upload all your video files. With those file, my Javascript has a for loop to create a button for each individual video found in that directory, then it puts the name of the file in the button. And all that works, now what I'm struggling with is creating an onclick event that gets the ID of the button that was pressed. I'm really struggling on doing this so any help would be appreciated.
My javascript:
var animepaths = [];
var animenames = [];
//FILE UPLOADING
const fileSelector = document.getElementById('file-selector');
fileSelector.addEventListener('change', (event) => {
const fileList = event.target.files;
filesLoop(fileList)
});
//loops through every file found in the directory
//and saves the path and file name to local storage
function filesLoop(files){
for(var x = 0; x < files.length; x++){
animepaths.push(files[x].webkitRelativePath)
animenames.push(files[x].name)
}
printOnScreen(animenames, animepaths)
}
//Creating a button with an H2 tag inside
//Then display it on screen in the container (display grid)
function printOnScreen(animenames, animepaths){
for(var x = 0; x < animenames.length; x++){
const elem = document.createElement('button');
elem.classList.add("grid-item");
const elemtext = document.createElement('h2')
elemtext.innerHTML = animenames[x]
elemtext.classList.add("grid-innertext")
elem.appendChild(elemtext)
document.getElementById('container').appendChild(elem);
}
}
If you have more than 1 button you should identify the group of buttons via a class not an id.
in your case it's even easier, as you create the button pro grammatically, so we could create the event there ...
//your function and some of my code
function printOnScreen(animenames, animepaths){
for(var x = 0; x < animenames.length; x++){
createAndAppendButton(animenames[x], animepaths[i]);
}
}
function createAndAppedButton(name, path) {
let button = document.createElement('button');
button.classList.add("grid-item");
button.innerText = name
document.getElementById('container').appendChild(button);
button.addEventListener("click", function() {
//do something with the path, which is accessible her
console.log(path)
});
}
As you can see I removed your h1, as H1 cannot be a child of the button-tag
In any DOM event handler, the element that triggered the event is available within the handler via the this keyword. Therefore, to get the id of the button that triggered the event, you'd just use: this.id.
Here's an example:
document.querySelector("button").addEventListener("click", function(){
console.log("The button's id is: " + this.id);
});
<button id="btn">Click Me</button>
Maybe you can use something like:
function onClick(animenameId) {
...
// your magic here
...
}
function printOnScreen(animenames, animepaths){
...
elem.onclick = onClick(animenames[x]);
...
}
What do you think?
Related
So, I want to show some details when I click the details button. I have used for loop to loop through the buttons but it makes it so that when I click a single button, rest of the buttons get clicked as well. I understand it happens because of the for loop. But how do I make all the buttons clickable using a loop but prevent all of them from getting clicked when I click one?
I'm super new to JavaScript.
function showDetails() {
for (let i = 0; i < allProducts.length; i++) {
const getHiddenDescription = document.getElementsByClassName("details");
getHiddenDescription[i].style = "display: block";
console.log("clicked");
}
}
const getDetails = document.querySelectorAll(".btn-details");
for (let i = 0; i < allProducts.length; i++) {
getDetails[i].addEventListener("click", showDetails);
}
You can select the button which triggered the event listener by using an optional parameter available in the event listener callback, often named event, like so.
function showDetails(event) {
clickedButton = event.currentTarget;
clickedbutton.style = "display: block";
}
How to convert a button click to a mouseup event in separate js files.
I have this button code in a html file (which is working without issue):
<button class="J_sheetControl" id="J_timingSubmit2">Submit</button>
When clicked it runs a function(?) in an external js file:
$("#J_timingSubmit2").click(function(ev){
var sheetStates = sheet.getSheetStates();
var rowsCount = 15;
var colsCount = 7;
var timesheetrowsdata = "";
var timesheetcoldata = "";
for(var row= 0, rowStates=[]; row<rowsCount; ++row){
rowStates = sheetStates[row];
timesheetrowsdata += rowStates+(row==rowsCount-1?'':',');
}
timesheetcoldata = timesheetrowsdata.replace(/,/g, '');
const testData = timesheetcoldata;
const dataArr = testData.match(/.{1,7}/g)
.map(s => Number(s[0])) // Only take the first char as a Number
let dataSum = dataArr.reduce((a, b) => a + b);
let isSameAsRowsCount = dataSum == rowsCount;
});
I want to convert this so it runs on a click of a table header (on the mouseup event).
This function is in a second js file (function call needs to be inserted at the end of the if statement):
thisSheet.delegate(".TimeSheet-colHead","mouseup.umsSheetEvent",function(ev){
if(!operationArea.startCell){
return;
}
var curColHead = $(ev.currentTarget);
const targetStateValue = localStorage.getItem('shiftstatus');
if (targetStateValue === "earlyshift") {
var endCell = [14,curColHead.data("col")];
var correctedCells = cellCompare(operationArea.startCell,endCell);
afterSelecting(ev,correctedCells);
//code needs to go here
}
I tried to rename it so it looks more like a standard function e.g. ColumnChecker()
But this just giving me errors that it was not a function on the above mouseup event.
I have resolved this but it does not seem the most tidy way (I have used similar twice already in the app). If no-one has a better solution I will use it as the answer.
var but_Open3 = document.getElementById("J_timingSubmit2");
J_timingSubmit2.click();
With jQuery you could just add another event listener for your mouseup event.
$("#J_timingSubmit2").mouseup( handler);
$("#J_timingSubmit2").on('mouseup', handler);
It seems this is not possible without a workaround.
I have hidden the button:
<button class="J_sheetControl" id="J_timingSubmit2" style="display:none;">Open Hidden>Submit</button>
I then call the button in the mouseup event (the original question):
J_timingSubmit2.click();
This then runs the function detailed above:
$("#J_timingSubmit2").click(function(ev){
I do not have access to the HTML of the pages (they are program-built dynamically).
I do have access to the JS page it is linked to.
For example I can do somethin like this and it works:
window.onload=function(){
var output = document.getElementById('main_co');
var i=1;
var val="";
while(i<=1)
{ if(!document.getElementById('timedrpact01'+i))
{
var ele = document.createElement("div"); ele.setAttribute("id","timedrpact01"+i);
ele.setAttribute("class","inner");
ele.innerHTML=" Hi there!" ;
output.appendChild(ele);
I would like to use this basis insert a button that would allow to switch from one CSS set (there are several files invoked) to another _another path.
Many thanks
The external stylesheets are referenced using link, as in:
<link rel="stylesheet" href="http://example.com/path-to-css">
So, get hold of the appropriate link element using:
var css = document.getElementsByTagName("link")[0];
Here, we got hold of the first link available by specifying the [0] index.
Then, overwrite the href attribute to point it to the new path.
css.setAttribute("href", "http://example.com/path-to-css");
window.onload=function(){
var output = document.getElementById('main_co');
var i=1;
var val="";
//switch all the href's to another path
var switchStyleSheet = function() {
var links = document.getElementsByTagName("link");
for(var i=0; lkC = links.length; i < lkC; i++)
links[0].href = links[0].href.replace('path_to_file', '_path_to_file');
};
while(i<=1) //while is not required here, if i is 1
{
if(!document.getElementById('timedrpact01'+i)) {
var ele = document.createElement("div"); ele.setAttribute("id","timedrpact01"+i);
ele.setAttribute("class","inner");
ele.innerHTML=" Hi there!" ;
var button = document.createElement('button');
if(button.addEventListener) {
button.addEventListener('click', switchStyleSheet);
}
else {
button.attachEvent('click', switchStyleSheet);
}
output.appendChild(button);
output.appendChild(ele);
}
}
}
Heres my code:
<div id="cmdt_1_1d" class="dt_state1" onclick="sel_test(this.id)">
<img id="cmdt_1_1i" onclick="dropit('cmdt_1_1');" src="/site/hitechpackaging/images/items/bags_menu.jpg ">
<span class="dt_link">
BAGS
</span>
</div>
Unfortunately I cannot modify this file, is there a way using javascript to disable the onclick from the img tag only.
I was using this script but it disable the onclick event from all images. But i want only from this component
var anchorElements = document.getElementsByTagName('img');
// for (var i in anchorElements)
// anchorElements[i].onclick = function() {
// alert(this.id);
// return false;
// }
Any ideas will be appreciated.
Edited:
Is there a way to stop the function dropit from executing, is it possible using javascript. On page load, etc.
another option is can i rename the img file using javascript??
document.getElementById('cmdt_1_1i').removeAttribute("onclick");
var eles = document.getElementById('cmdt_1_1d').getElementsByTagName('img');
for (var i=0; i < eles.length; i++)
eles[i].onclick = function() {
return false;
}
Lots of answers, but the simplest is:
document.getElementById('cmdt_1_1i').onclick = '';
try something like this:
var badImage = document.getElementById("cmdt_1_1i");
badImage.onclick = null;
badImage.addEventlistener("click",function(e){
e.preventDefault();
e.stopPropagation();
return null;
},true);
If you later need to restore the onclick property, you can save it in a field before overwriting it:
document.getElementById(id).saved=document.getElementById(id).onclick;
document.getElementById(id).onclick = '';
so that later you can restore it:
document.getElementById(id).onclick=document.getElementById(id).saved;
This can be useful especially in the case, in which the original onclick property contained some dynamically computed value.
You can programmatically reassign event listeners. So in this case, it might look something like:
const images = document.querySelectorAll('#cmdt_1_1d img')
for (let i = 0; i < images.length; i++) {
images[i].onclick = function() => {}
}
...where the query above returns all of the img tags that are descendants of the element with ID cmdt_1_1d, and reassigns each of their onclick listeners to an empty function. Therefore no actions will take place when those images are clicked.
function init()
{
alert("init()");
/**
* Adds an event listener to onclick event on the start button.
*/
xbEvent.addEventListener(document.getElementById("viewInvitation"), "click", function()
{
new Ajax().sendRequest("31260xml/invitations.xml", null, new PageMaster());
xbEvent.addEventListener(document.getElementById("declinebutton"), "click", function ()
{
declineInvitation();
});
});
ok so what I have here is a event listerner function, the case is when viewInvitation is clicked , the program will fetch my xml file and run page master function where I created my decline button with id="declinebutton", however this does not work, the error message that i get is obj=null or the program could not find id = declinebutton, why is it so? I have created it when I called page master using dom. any help will be appreciated.
function PageMaster()
{
this.contentDiv = document.getElementById("content");
}
/**
* Builds the main part of the web page based on the given XML document object
*
* #param {Object} xmlDoc the given XML document object
*/
var subjectList;
var i;
PageMaster.prototype.doIt = function(xmlDoc)
{
alert("PageMaster()");
alert("Clear page...");
this.contentDiv.innerHTML = "";
if (null != xmlDoc)
{
alert("Build page...");
//create div Post
var divPost = document.createElement("div");
divPost.className = "post";
//create h1 element
var h1Element = document.createElement("h1");
var headingText = document.createTextNode("Invitations");
h1Element.appendChild(headingText);
//insert h1 element into div post
divPost.appendChild(h1Element);
subjectList = xmlDoc.getElementsByTagName("subject");
var groupList = xmlDoc.getElementsByTagName("group");
for (i = 0; i < subjectList.length; i++) //for each subject
{
var divEntry = document.createElement("div");
divEntry.className = "entry";
var subjectNum = subjectList[i].attributes[0].nodeValue;
var subjectName = subjectList[i].attributes[1].nodeValue;
var groupId = groupList[i].attributes[0].nodeValue;
var groupName = groupList[i].attributes[1].nodeValue;
var ownerId = groupList[i].attributes[2].nodeValue;
//set up the invitation table attributes
var table=document.createElement("table");
table.width = 411;
table.border = 3;
table.borderColor = "#990000"
var input=document.createElement("p");
var inputText=document.createTextNode("You are invited to join " + groupName + "(groupId : " + groupId +")");
input.className="style11";
var blank=document.createElement("nbps");
input.appendChild(inputText);
var acceptButton=document.createElement("input");
acceptButton.type="button";
acceptButton.id="acceptbutton";
acceptButton.value="accept";
var declineButton=document.createElement("input");
declineButton.type="button";
declineButton.id="declinebutton";
declineButton.value="decline";
table.appendChild(input);
table.appendChild(acceptButton);
table.appendChild(declineButton);
divEntry.appendChild(table);
var blankSpace = document.createElement("p");
divEntry.appendChild(blankSpace);
divPost.appendChild(divEntry);
}
//insert div post into div content
this.contentDiv.appendChild(divPost);
}
};
/**function getValueOf()
{
return i;
}**/
function declineInvitation()
{
alert("decline");
}
function acceptInvitation()
{
alert("hello");
/**var pos=getValueOf();
alert(subjectList[pos].attributes[0].nodeValue);**/
}
That's my page master function, and I definitely have created the button. but it does not work.
Try calling your function like this:
window.onload=init;
The javascript runs as the page loads. At that point, the element does not yet exist in the DOM tree. You'll need to delay the script until the page has loaded.
The example you gave doesn't create the "Decline" button, as your question suggests it should. If it should, you might want to look at that.
Of course, if the button already exists, please disregard this answer.
You have a listener inside a listener. Is that right?
What about this?:
function init(){
alert("init()");
/** * Adds an event listener to onclick event on the start button. */
xbEvent.addEventListener(document.getElementById("viewInvitation"), "click", function()
{
new Ajax().sendRequest("31260xml/invitations.xml", null, new PageMaster());
}
xbEvent.addEventListener(document.getElementById("declinebutton"), "click", function ()
{
declineInvitation();
});
As far as I understand, you create button with id="declinebutton" for each entry from xml, is that right?
If yes, I'd suggest you to generate different id's for each button (for example, append line index to 'declinebutton', so you have buttons 'declinebutton0', 'declinebutton1' an so on), and assign event listener to buttons separately in the loop.