I have created an application where elements from the toolbox can be dragged and dropped onto a canvas and their properties can be set as soon as they are dropped. But, I have an instance where when the "stream ui-draggable" element is dropped on the canvas I disable the canvas and the toolbox and display a properties panel where the user can select a predefined stream for the newly dropped element and also give it another name under the "as : " text field. This name should then replace the currently displayed- disabled name "Element" with the name provided bu the user. Is there a way that I can replace this text in the dropped element.
js function:
drop: function (e, ui) {
var dropElem = ui.draggable.attr('class');
droppedElement = ui.helper.clone();
ui.helper.remove();
$(droppedElement).removeAttr("class");
jsPlumb.repaint(ui.helper);
if(dropElem=="stream ui-draggable")
{
var newAgent = $('<div>').attr('id', i).addClass('streamdrop');
//alert("newAgent ID: "+newAgent.attr('id'));
clickedId = newAgent.attr("id");
alert("clicked ID: "+i);
createStreamForm();
$("#container").addClass("disabledbutton");
$("#toolbox").addClass("disabledbutton");
$(droppedElement).draggable({containment: "container"});
var prop = $('<a class="streamproperty" onclick="doclick(this)"><b><img src="../Images/settings.png"></b></a> ').attr('id', (i));
var finalElement= newAgent.text("Element").append('<a class="boxclose" id="boxclose"><b><img src="../Images/Cancel.png"></b></a> ').append(prop);
//Increment the Element sequence number
i++; r++; q++;
var l = ($(finalElement).attr('id'));
alert("Final elm id: "+finalElement.attr('id'));
var connection = $('<div>').attr('id', l + '-' + q).addClass('connection');
finalElement.css({
'top': e.pageY,
'left': e.pageX
});
finalElement.append(connection);
$('#container').append(finalElement);
jsPlumb.draggable(finalElement, {
containment: 'parent'
});
jsPlumb.makeTarget(connection, {
anchor: 'Continuous'
});
jsPlumb.makeSource(connection, {
anchor: 'Continuous'
});
}
The createStreamForm() function:
var importDiv, iStreamtype, br, istreamlbl, istreamtypelbl, iPredefStreamdiv, istreamDefLineDiv, istreamDefDivx, istreamName, importbtn;
var exportDiv,eStreamtype, estreamlbl, estreamtypelbl, ePredefStreamdiv, estreamDefLineDiv, estreamDefDivx, estreamName, exportbtn;
var streamDiv, streambtn;
var definestreamdiv,inputval;
function createStreamForm()
{
$(".toolbox-titlex").show();
$(".panel").show();
//For the Import Form
importDiv = document.createElement("div");
iStreamtype = document.createElement("div");
br = document.createElement("br");
istreamlbl = document.createElement("label");
istreamtypelbl = document.createElement("label");
iPredefStreamdiv = document.createElement("div");
istreamDefLineDiv = document.createElement("div");
istreamDefDivx = document.createElement("div");
istreamName = document.createElement("input");
importbtn = document.createElement("button");
importDiv.className = "importdiv";
importDiv.id = "importdiv";
istreamlbl.className = "lblfloat-left";
br.className = "br-div";
istreamlbl.innerHTML = "Stream:";
iPredefStreamdiv.id = "PredefinedStream1";
istreamDefDivx.className = "streamDefDiv";
istreamDefDivx.id = "streamDefLineDiv";
istreamName.className = "panel-input-streamName";
istreamName.id = "istreamName";
istreamName.placeholder = "as : ";
importbtn.type = 'button';
importbtn.innerHTML = "Import";
importbtn.className = "btn-import";
importbtn.setAttribute("onclick","storeImportStreamInfo()");
importDiv.appendChild(iStreamtype);
importDiv.appendChild(istreamlbl);
importDiv.appendChild(istreamtypelbl);
importDiv.appendChild(iPredefStreamdiv);
importDiv.appendChild(br);
importDiv.appendChild(istreamDefLineDiv);
importDiv.appendChild(istreamDefDivx);
importDiv.appendChild(br);
importDiv.appendChild(istreamName);
importDiv.appendChild(br);
importDiv.appendChild(importbtn);
importDiv.appendChild(br);
//For the Export Form
exportDiv = document.createElement("div");
eStreamtype = document.createElement("div");
br = document.createElement("br");
estreamlbl = document.createElement("label");
estreamtypelbl = document.createElement("label");
ePredefStreamdiv = document.createElement("div");
estreamDefLineDiv = document.createElement("div");
estreamDefDivx = document.createElement("div");
estreamName = document.createElement("input");
exportbtn = document.createElement("button");
exportDiv.className = "exportdiv";
exportDiv.id = "exportdiv";
estreamlbl.className = "lblfloat-left";
estreamlbl.innerHTML = "Stream:";
ePredefStreamdiv.id = "PredefinedStream2";
estreamDefDivx.className = "streamDefDiv";
estreamDefDivx.id = "streamDefLineDiv";
estreamName.className = "panel-input-streamName";
estreamName.id = "panel-input-streamName";
estreamName.placeholder = "as : ";
exportbtn.type = 'button';
exportbtn.innerHTML = "Export";
exportbtn.className = "btn-export";
exportDiv.appendChild(estreamlbl);
exportDiv.appendChild(estreamtypelbl);
exportDiv.appendChild(ePredefStreamdiv);
exportDiv.appendChild(br);
exportDiv.appendChild(estreamDefLineDiv);
exportDiv.appendChild(estreamDefDivx);
exportDiv.appendChild(br);
exportDiv.appendChild(estreamName);
exportDiv.appendChild(br);
exportDiv.appendChild(exportbtn);
exportDiv.appendChild(br);
//For the Stream Form
streamDiv = document.createElement("div");
streambtn = document.createElement("button");
definestreamdiv = document.createElement("div");
inputval = document.createElement("div");
streambtn.type = 'button';
streamDiv.className = "streamdiv";
streamDiv.id = "streamdiv";
streambtn.innerHTML = "Define Stream";
streambtn.className = "btn-define-stream";
streambtn.setAttribute("onclick","createattribute()");
//inputval.innerHTML = "Provide a Stream name and click to add attribute-type pairs to yours stream.";
streamDiv.appendChild(streambtn);
definestreamdiv.appendChild(inputval);
lot.appendChild(importDiv);
createattr();
lot.appendChild(exportDiv);
lot.appendChild(streamDiv);
lot.appendChild(definestreamdiv);
}
storeImportStreamInfo() Function:
var clickcount=1;
function storeImportStreamInfo()
{
var choice=document.getElementById("streamSelect");
var selectedStream = choice.options[choice.selectedIndex].text;
var asName= document.getElementById("istreamName").value;
var StreamElementID = clickcount;
clickcount++;
createdImportStreamArray[clickedId][0]=StreamElementID;
createdImportStreamArray[clickedId][1]=selectedStream;
createdImportStreamArray[clickedId][2]=asName;
y++;
}
Solved it by passing the newly dropped jsPlumb object to the storeImportStreamInfo() as parameters and set the text within the method. Also this parameter needs to be carried through all the functions through which it progresses before achieving the storeImportStreamInfo() method.
Eg:
function createStreamForm(newAgent,i)
within this function->
importbtn.onclick = function() {
storeImportStreamInfo(newAgent,i);
}
and so on. In the storeImportStreamInfo() function, I've added the lines that append the icons and the text to the dropped Element.
var prop = $('<a class="streamproperty" onclick="doclick(this)"><b><img src="../Images/settings.png"></b></a> ').attr('id', (i));
newAgent.text(asName).append('<a class="boxclose" id="boxclose"><b><img src="../Images/Cancel.png"></b></a> ').append(prop);
Related
I have a basic film search, now I'm trying to make it so that once you click on a film, it gets just that clicked films title property, at the moment it is bringing every film from the list of films that match the search term.
How do I go about finding out which film has been clicked and ONLY pass this objects properties through instead of every object? Do I need to use a loop?
screenshots added, e.g if I click the first film "John Wick" it creates a h1 title for every film title that has "John Wick"
function search() {
var userInput = $("#content-container-search").val().replace(/\s+/g,"%20");
var searchTerm = "".concat(standardURL, apiKey, 'query=', userInput);
var request = new XMLHttpRequest();
clear(); //runs the clear function to clear existing DOM results to make way for the new ones
request.open('GET', searchTerm , true);
request.onload = function(data) {
var data = JSON.parse(this.response);
createList(data);
}
request.send();
}
function createList(data){
var app = document.getElementById("film-results");
data.results.forEach(film => {
console.log(film.title);
var filmInfo = film;
var Filmcontainer = document.createElement("div");
Filmcontainer.setAttribute("class", "row film-container");
var filmContainerLeftPanel = document.createElement("div");
filmContainerLeftPanel.setAttribute("class", "film-container-left-panel column small-3");
var filmContainerRightPanel = document.createElement("div");
filmContainerRightPanel.setAttribute("class", "film-container-right-panel column small-9");
var li = document.createElement("li");
li.setAttribute("class", "film-container-right-panel-li");
var ul = document.createElement("ul");
var h1 = document.createElement("h1");
h1.setAttribute("class", "film-container-right-panel-h1");
h1.textContent = film.title;
var ahref = document.createElement("a");
// ahref.setAttribute("class", "button");
ahref.setAttribute("data-open", "exampleModal1");
var paragraph = document.createElement("p");
paragraph.setAttribute("class", "film-container-right-panel-p");
var paragraphMaxLength = 125;
var filmOverview = film.overview;
var trimmedFilmOverview = filmOverview.substr(0, paragraphMaxLength);
trimmedFilmOverview = trimmedFilmOverview.substr(0, Math.min(trimmedFilmOverview.length, trimmedFilmOverview.lastIndexOf(" ")));
trimmedFilmOverview = trimmedFilmOverview + "...";
paragraph.textContent = trimmedFilmOverview;
var baseImgURL = "https://image.tmdb.org/t/p/w154" + film.poster_path;
var filmImage = document.createElement("img");
filmImage.src = baseImgURL;
filmImage.setAttribute("class", "film-container-right-panel-img");
// film.forEach(filmImage.src.indexOf("null"))
// filmImage.src = "/img/imagenotavailable.png";
app.appendChild(Filmcontainer);
Filmcontainer.appendChild(filmContainerLeftPanel);
Filmcontainer.appendChild(filmContainerRightPanel);
filmContainerLeftPanel.appendChild(filmImage);
filmContainerRightPanel.appendChild(ul)
.appendChild(li)
.appendChild(ahref)
.appendChild(h1);
li.appendChild(paragraph);
generateModal(filmInfo);
})
}
function generateModal(filmInfo){
var modal = document.getElementById("exampleModal1");
var h1 = document.createElement("h1");
h1.textContent = filmInfo.title;
modal.appendChild(h1);
console.log(filmInfo);
}
Maybe you want to take a look at Event.target and currentTarget.
--UPDATE--
Here is an example:
let ctas = document.querySelectorAll('.see-details');
ctas.forEach(cta => {
cta.addEventListener('click', (movie) => {
let movieId = movie.target.getAttribute('data-movie-id');
console.log(movieId);
});
});
<button data-movie-id="toy-story-1" class="see-details">See movie details</button>
You can solve this problem using event.target in JavaScript.
var div = document.createElement('div');
document.body.appendChild(div);
var button = document.createElement("button");
button.innerHTML = "John Wick";
button.style.margin= "10px";
div.appendChild(button);
var button2 = document.createElement("button");
button2.innerHTML = "John Wick: chapter 2";
button2.style.margin= "10px";
div.appendChild(button2);
var button3 = document.createElement("button");
button3.innerHTML = "John Wick: chapter 3";
div.appendChild(button3);
function showName(e){
alert("you have clicked "+e.target.innerHTML);
}
div.addEventListener('click', showName, false);
In this code I have created 3 buttons and whenever you clicks on any button it will trigger an event showName and event.target helps us to get the element that triggered a specific event (i.e click in our case) .
and try to run console.log(event.target), this will give you the whole information about the event triggered here.
I hope this helps.
I need help to create jQuery mobile button using JavaScript, I am using the code below, it creates a button but it is not recognizing the jQuery mobile style.
thanks for your help :)
function SubmitForm() {
var list = document.getElementById("forMore"); // Get the <ul> element with id="forMore"
if (list.hasChildNodes()) { // It has at least one
list.removeChild(list.childNodes[0]);
}
var e = document.getElementById("services");
var strUser = e.options[e.selectedIndex].value;
var id = e.options[e.selectedIndex].id;
document.getElementById("desc").innerHTML = strUser;
document.getElementById("fields").style.visibility = "visible";
var td = document.getElementById('forMore');
var btn = document.createElement('input');
btn.setAttribute("data-role", "button");
btn.setAttribute("data-theme", "b");
btn.setAttribute("class", "ui-input-btn");
btn.style.cssFloat = "left";
btn.style.fontSize = "18px";
btn.style.fontFamily = "myAccountFont";
btn.style.color = "green";
btn.onclick = function () {
location.href = "/Pin/SendVas?id=" + id;
};
btn.value = "تفعيل";
td.appendChild(btn);
}
hope this will help:
var a = document.createElement("A");
a.appendChild(document.createTextNode("Name"));
a.setAttribute("data-role","button");
a.setAttribute("data-inline","true");
a.setAttribute("data-corner","false");
$(td).append(a).trigger('create');
//Or user parent container:
$("#container").trigger('create');
I have a practice app that is supposed to accept new information and put the information into an array of objects. It also has the option to edit specific data in the array. Everything works perfectly until I try and re-insert the new information back to where the old information was stored inside the array. The problem is occurring in the editObj function. I removed all the bad code I knew existed and left what I know works.
//HTML elements
var table = document.querySelector('#list');
var main = document.querySelector('#main');
var form = document.querySelector('#form');
var userInput = document.querySelector('#userInput');
var addBtn = document.querySelector('#add');
var saveBtn = document.querySelector('#save');
//Object array
var Assignments = [ ];
//main function
var mainView = function() {
table.innerHTML = '';
for(i = 0; i < Assignments.length; i++){
//elements
var row = document.createElement('tr');
var data = document.createElement('td');
var data2 = document.createElement('td');
var data3 = document.createElement('td');
var edit = document.createElement('td');
var remove = document.createElement('td');
var editBtn = document.createElement('button');
var deleteBtn = document.createElement('button');
//rendering
data.innerHTML = Assignments[i].name;
data2.innerHTML = Assignments[i].possible;
data3.innerHTML = Assignments[i].earned;
//innerText
editBtn.innerText = "Edit";
deleteBtn.innerText = "Delete";
//set attributes
editBtn.setAttribute('index',i);
deleteBtn.setAttribute('index',i);
//appending
edit.appendChild(editBtn);
remove.appendChild(deleteBtn);
row.appendChild(data);
row.appendChild(data2);
row.appendChild(data3);
row.appendChild(edit);
row.appendChild(remove);
table.appendChild(row);
//event listeners
editBtn.addEventListener('click', editObj);
deleteBtn.addEventListener('click', deleteObj);
//unhide table
main.style.display = '';
}
};
//add form
var addObj = function() {
main.style.display = 'none';
form.style.display = '';
};
var saveObj = function(e) {
e.preventDefault();
var itmObj = {};
var name = 'name';
var pP = 'possible';
var pE = 'earned';
itmObj[name] = userInput.name.value;
itmObj[pP] = userInput.pP.value;
itmObj[pE] = userInput.pE.value;
Assignments.push(itmObj);
console.log(Assignments);
form.style.display = 'none';
mainView();
};
//editing functions
var editObj = function(e) {
main.style.display = 'none';
form.style.display = '';
saveBtn.style.display = 'none';
newSaveBtn.style.display = '';
//get object
var editing = e.currentTarget.getAttribute('index');
userInput.name.value = Assignments[editing].name;
userInput.pP.value = Assignments[editing].possible;
userInput.pE.value = Assignments[editing].earned;
//remove original from array
Assignments.splice(editing, 1);
//add new data to array
};
//delete
var deleteObj = function(e) {
var removing = e.currentTarget.getAttribute('index');
Assignments.splice(removing, 1);
mainView();
};
//event listeners
addBtn.addEventListener('click', addObj);
userInput.addEventListener('submit', saveObj);
Assuming nothing is wrong with the current code... How do I get the new updated information back to the previous indexed value?
This was one of the ways that I tried and the eventListener will not fire on the new button:
var editObj = function(e) {
main.style.display = 'none';
form.style.display = '';
saveBtn.style.display = 'none';
//get object
var editing = e.currentTarget.getAttribute('index');
userInput.name.value = Assignments[editing].name;
userInput.pP.value = Assignments[editing].possible;
userInput.pE.value = Assignments[editing].earned;
//remove original from array
Assignments.splice(editing, 1);
//add new data to array
var editBtn = document.createElement('button');
editBtn.innerText = 'Save New';
form.appendChild(editBtn);
editBtn.addEventListener('click', editTest);
//test editing
var editTest = function(e){
console.log(editing);
var newObj = {};
var newName = 'name';
var newpP = 'possible';
var newpE = 'earned';
newObj[newName] = userInput.name.value;
newObj[newpP] = userInput.pP.value;
newObj[newpE] = userInput.pE.value;
Assignments.splice(editing, 0, newObj);
form.style.display = 'none';
form.removeChild(editBtn);
saveBtn.style.display = '';
mainView();
};
};
Ah! Fixed it. Turns out the editObj and editTest functions needed to be combined. Here is the working code:
var editObj = function(e) {
main.style.display = 'none';
form.style.display = '';
saveBtn.style.display = 'none';
//get object
var editing = e.currentTarget.getAttribute('index');
userInput.name.value = Assignments[editing].name;
userInput.pP.value = Assignments[editing].possible;
userInput.pE.value = Assignments[editing].earned;
//remove original from array
Assignments.splice(editing, 1);
//add new data to array
var editBtn = document.createElement('button');
editBtn.innerText = 'Save New';
form.appendChild(editBtn);
editBtn.addEventListener('click', function(e){
console.log(editing);
var newObj = {};
var newName = 'name';
var newpP = 'possible';
var newpE = 'earned';
newObj[newName] = userInput.name.value;
newObj[newpP] = userInput.pP.value;
newObj[newpE] = userInput.pE.value;
Assignments.splice(editing, 0, newObj);
form.style.display = 'none';
form.removeChild(editBtn);
saveBtn.style.display = '';
mainView();
});
I wanted to make a js code that generate a list about the selected pictures, with the thumb, filename and filesize of the current picture. But something wrong, because I cannot reach the filename and filesize, because the eventListener doesnt see it. Any solution?
$('#media_uploader').change( function() {
var files = document.getElementById("media_uploader").files;
var output = document.getElementById("info");
output.innerHTML = '';
for(var i = 0; i< files.length; i++)
{
var file = files[i];
if( !file.type.match('image') )
continue;
var picReader = new FileReader();
picReader.addEventListener("load",function(event){
var picFile = event.target;
var div = document.createElement("div");
div.innerHTML = '<img src="' + picFile.result + '" />';
var lineNode = document.createElement('div');
lineNode.setAttribute('class','uploaded_file_line');
var fileThbDivNode = document.createElement('div');
fileThbDivNode.setAttribute('class','uploaded_file_thb');
fileThbDivNode.appendChild(div);
lineNode.appendChild( fileThbDivNode );
var fileNameDivNode = document.createElement('div');
fileNameDivNode.setAttribute('class','uploaded_file_name');
var fileNameNode = document.createElement('input');
fileNameNode.setAttribute('value',picFile.name);
fileNameDivNode.appendChild( fileNameNode );
lineNode.appendChild( fileNameDivNode );
var fileExtensionDivNode = document.createElement('div');
fileExtensionDivNode.setAttribute('class','uploaded_file_extension');
var fileExtensionNode = document.createElement('span');
fileExtensionNode.innerHTML = "JPG";
fileExtensionDivNode.appendChild( fileExtensionNode );
lineNode.appendChild( fileExtensionDivNode );
var fileSizeDivNode = document.createElement('div');
fileSizeDivNode.setAttribute('class','uploaded_file_size');
var fileSizeNode = document.createElement('span');
fileSizeNode.innerHTML = Number((((picFile.size)/1024)/1024).toFixed(3)) + " Mbytes";
fileSizeDivNode.appendChild( fileSizeNode );
lineNode.appendChild( fileSizeDivNode );
var clearDivNode = document.createElement('div');
clearDivNode.setAttribute('class','clear');
lineNode.appendChild( clearDivNode );
output.appendChild( lineNode );
});
picReader.readAsDataURL(file);
}
});
Try declaring var files outside of the change function
I think something like this may work for you
var stuffIcannotSee;
var my_func=function(importStuff){
return function(e){
alert(importStuff + "This is now in the context of the function");
};
}(stuffIcannotSee);
$('#media_uploader').change( my_func);
i got an anchor in the DOM and the following code replaces it with a fancy button. This works well but if i want more buttons it crashes. Can I do it without a for-loop?
$(document).ready(buttonize);
function buttonize(){
//alert(buttonAmount);
//Lookup for the classes
var button = $('a.makeabutton');
var buttonContent = button.text();
var buttonStyle = button.attr('class');
var link = button.attr('href');
var linkTarget = button.attr('target');
var toSearchFor = 'makeabutton';
var toReplaceWith = 'buttonize';
var searchButtonStyle = buttonStyle.search(toSearchFor);
if (searchButtonStyle != -1) {
//When class 'makeabutton' is found in string, build the new classname
newButtonStyle = buttonStyle.replace(toSearchFor, toReplaceWith);
button.replaceWith('<span class="'+newButtonStyle
+'"><span class="left"></span><span class="body">'
+buttonContent+'</span><span class="right"></span></span>');
$('.buttonize').click(function(e){
if (linkTarget == '_blank') {
window.open(link);
}
else window.location = link;
});
}
}
Use the each method because you are fetching a collection of elements (even if its just one)
var button = $('a.makeabutton');
button.each(function () {
var btn = $(this);
var buttonContent = btn.text();
var buttonStyle = btn.attr('class');
var link = btn.attr('href');
var linkTarget = btn.attr('target');
var toSearchFor = 'makeabutton';
var toReplaceWith = 'buttonize';
var searchButtonStyle = buttonStyle.search(toSearchFor);
...
};
the each method loops through all the elements that were retrieved, and you can use the this keyword to refer to the current element in the loop
var button = $('a.makeabutton');
This code returns a jQuery object which contains all the matching anchors. You need to loop through them using .each:
$(document).ready(buttonize);
function buttonize() {
//alert(buttonAmount);
//Lookup for the classes
var $buttons = $('a.makeabutton');
$buttons.each(function() {
var button = $(this);
var buttonContent = button.text();
var buttonStyle = button.attr('class');
var link = button.attr('href');
var linkTarget = button.attr('target');
var toSearchFor = 'makeabutton';
var toReplaceWith = 'buttonize';
var searchButtonStyle = buttonStyle.search(toSearchFor);
if (searchButtonStyle != -1) {
newButtonStyle = buttonStyle.replace(toSearchFor, toReplaceWith);
button.replaceWith('<span class="'
+ newButtonStyle
+ '"><span class="left"></span><span class="body">'
+ buttonContent
+ '</span><span class="right"></span></span>');
$('.buttonize').click(function(e) {
if (linkTarget == '_blank') {
window.open(link);
} else window.location = link;
}); // end click
} // end if
}); // end each
}