I am working on a project to move div elements around and update their id.
It calls the script and passes the tag's id number. So far it completely works that far. It moves the element up one place and swaps the div id numbers. The only thing is that when I click on the same div to move it again (like moving div#3 to spot#1 by clicking "up" a second time), It doesn't respond to the new div "id" even though it appears to be successfully changed when i inspect it in the browser.
The javascript: just showing the if up
enter code here
$("#content_update").on("click", ".rowupdown", function(){
// button is up or down
var upordown = $(this).attr('value');
// id number of div from button
var number = $(this).attr('id');
// current div can edit id
var $moveid = $("div#row" + number);
var numberint = parseInt(number);
if (upordown == "up") {
var s = numberint - 1;
//number of div to place before and to set id with
var numberstring = s.toString();
//***ability to select the other div element***
var $diffrow = "div#row" + numberstring;
//** update current div id***
var $editcurrent = "div#row" + number;
// puts other div id into this one
var newid = "row" + numberstring;
// puts in this id to the other div
var editother = "row" + number;
$($diffrow).before($moveid); // finally moves the current div up one
$($diffrow).attr("id", editother);
$($editcurrent).attr("id", newid); //changes id of current div to one before
}
});
the HTML (i have a button that adds new divs and adds 1 to give them a unique id, first click=1 second makes div id = 2 and so on, it doesn't have to do with the question though.)
case "row":
if (!isset($_SESSION["rownumber"])){
$row = $_SESSION["rownumber"] = 1;
}
$row = $_SESSION["rownumber"]++;
echo " the html
<div class='panel panel-default' id='row".$row."'>
<button class='rowupdown point' id='".$row."' value='up'>up</button>
</div>
Related
I have two buttons SHOW and HIDE. When show is clicked numbers will appear (which are json files, each json file contain only one number 1, 2, 3..) when HIDE is clicked first number(json) in a row dissapear. For example we clicked SHOW button 3 times and got this: 1 2 3 and then clicked HIDE once then we got: 2 3 shown. My problem is when HIDE is clicked I want to save that hidden number by showing it in my div where id="nome". After another clicking on button HIDE another hidden number is shown and old is deleted from div. I tried this:
var pageCounter = 1;
var pageCounterr = 1;
var animalContainer = document.getElementById("animal-info");
var animalContainerr = document.getElementById("nome");
var btn = document.getElementById("btn");
var btnn = document.getElementById("btnn");
btn.addEventListener("click", function(){
var ourRequest = new XMLHttpRequest();
ourRequest.open('GET','http://10.0.9.243/animals-'+ pageCounter + '.json');
ourRequest.onload = function(){
var ourData = JSON.parse(ourRequest.responseText);
renderHTML(ourData);
};
ourRequest.send();
pageCounter++;
});
function renderHTML(data) {
var htmlString = document.createElement("div");
for (i=0; i < data.length; i++){
let pText = document.createTextNode(data[i].name);
let pElement = document.createElement("p");
pElement.append(pText);
htmlString.append(pElement);
htmlString.classList.add('containers') // new Line added
}
animalContainer.append(htmlString);
}
btnn.addEventListener("click", function(){
let containers = document.getElementsByClassName('containers');
if(containers.length > 0){
document.getElementById("nome").innerHTML = containers[0];
containers[0].remove();
}
});
<button id="btn">SHOW</button>
<button id="btnn">HIDE</button>
<h2>Numbers:</h2>
<div id="animal-info"></div>
<h2>Hidden number is:</h2>
<div id="nome"></div>
And what I get as a result is ' [object HTMLDivElement] ' in div with id="nome".
The only thing that is wrong is the used logic, look this:
When you get elements by class name "container" you are getting a array of this:
var htmlString = document.createElement("div");
Cause you defined that element's class to:
htmlString.classList.add('containers')
Then you're just getting div.
Solution:
Inside of this element you have a "p" element, and inside it you have a textNode with the content that you want!
Simple, good programming for you.
I have an HTML document with 6 Divs, I've written a javascript code that changes the heading depending on which div is selected (6 vars and 6 functions) e.g.
var divSelect = document.getElementById("firstDiv");
divSelect.onclick = function () {
var mainHeading = document.getElementById("heading");
mainHeading.innerHTML = "You have selected the first option";
};
I then have an anchor div which is linking to another HTML page, when it opens I want it to know which div was selected from the first HTML page, and then input a new heading based on the selection.
So I need to know which of the six functions was actioned based on the div that was clicked.
Any help much appreciated.
You can pass it in url query. Passing for example id parameter, like this: http://example.com/secondpage.html?firstpagedivid=firstDiv And then on second page you can parse url to get div id or whatever parameter you passed.
Here you can find how to get url parameter on second page: link
Html:
<div class="clickable" id="firstDiv">first</div>
<div class="clickable" id="secondDiv">second</div>
<div class="clickable" id="thirdDiv">third</div>
<br>
<div id="heading"></div>
<br>
<a id="navigator" href="second.html">Next page</a>
Javascript:
(function() {
var currentSelectedDiv;
var heading = document.getElementById('heading');
var navigator = document.getElementById('navigator');
var divs = document.querySelectorAll('.clickable');
for(var i=0; i<divs.length; i++) {
divs[i].onclick = function(e) {
var target = e.target;
currentSelectedDiv = target.getAttribute('id');
heading.innerHTML = ['You have selected ', currentSelectedDiv].join('');
}
}
navigator.onclick = function(e) {
e.preventDefault();
var a = e.target;
var href = a.getAttribute('href');
href += '?previousPageDivId=' + currentSelectedDiv;
alert(href);
//Just uncomment line below
//document.location.href = href;
}
})();
Here you have working example: https://jsfiddle.net/3wdzh2d4/
I am working on a quizz test. I want to select the last element on the page with a specific class so that when the user clicks on it the result of the quizz appears. Right now I'm doing it by adding an extra class but I wanted to know if there's a way of traversing the document without the use of classes so that no matter how many questions are added to the quizz the function will be triggered when the last element is clicked. I tried the solutions suggested here and here but it doesn't seem to work. Thanks
I created the following codepen for it
//get total of questions
var $questionNumber = $('h2').length;
console.log($questionNumber);
//caching final score
var $totalScore=0;
$('li').click(function(){
//caching variables
var $parent = $(this).parent();
var $span = $(this).find('.fa');
//deactivate options on click
$parent.find('li').off("click");
//check for .correct class
//if yes
if($(this).hasClass('correct')){
//add .correctAnswer class
$(this).addClass('correctAnswer');
//find next span and change icon
$span.removeClass('fa fa-square-o').addClass('fa fa-check-square-o');
//reduce opacity of siblings
$(this).siblings().addClass('fade');
//show answer
var $answerReveal= $parent.next('.answerReveal').show();
var $toShowCorrect = $answerReveal.find('.quizzAnswerC');
var $toShowFalse = $answerReveal.find('.quizzAnswerF');
$toShowCorrect.show();
$toShowFalse.remove();
//add 1 to total score
$totalScore+=1;
//console.log($totalScore);
}else{
//add .wrongAnswer class
$(this).addClass('wrongAnswer').addClass('fade');
//change icon
$span.removeClass('fa fa-square-o').addClass('fa fa-check-square-o');
//reduce opacity of its siblings
$(this).siblings().addClass('fade');
//show wrong Message
var $answerReveal= $parent.next('.answerReveal').show();
var $toShowCorrect = $answerReveal.find('.quizzAnswerC');
var $toShowFalse = $answerReveal.find('.quizzAnswerF');
$toShowCorrect.remove();
$toShowFalse.show();
//locate correct and highlight
$parent.find('.correct').addClass('correctAnswer');
};
});//end click function
//print Results
function printResult(){
var resultText = '<p>';
if ($totalScore === $questionNumber){
resultText+='You got '+ $totalScore+ ' out of '+$questionNumber+'! </p>';
$('.resultContainer').append(resultText);
$('#halfText').append('<p>This is awesome!</p>');
$('#halfImage').append('<img src="http://placehold.it/350x150" width="100%"><img>');
}else if($totalScore>=3 && $totalScore < $questionNumber){
resultText+='You got '+ $totalScore+ ' out of '+$questionNumber+'! </p>';
$('.resultContainer').append(resultText);
$('#halfText').append('<p>So and so...better luck next time</p>');
$('#halfImage').append('<img src="http://placehold.it/350x150" width="100%"><img>');
}else if ($totalScore<3){
resultText+='You got '+ $totalScore+ ' out of '+$questionNumber+' </p>';
$('.resultContainer').append(resultText);
$('#halfText').append('<p>No..no...no...you have to try harder</p>');
$('#halfImage').append('<img src="http://placehold.it/350x150" width="100%"><img>');
}
};//end function
//final score
$('li.last').click(function(){
//show result after last li is clicked
var $height = $('.finalResult').height();
printResult();
console.log($totalScore)
$('.finalResult').show();
$('html, body').animate({
scrollTop: $(document).height()-$height},
1400);
});
Getting the last element with a given class is very straightforward with jQuery:
$('selector').last().click(...);
you can select last element with class using:
$( ".classname:last-child" ).click(function(){});
JS only. On mouseover I'm calling a function I made that creates a div element with an image inside.
I pass (this) as a parameter to the function. The function works and onmouseover it creates a child element and I can click it. However, If I add on mouse out of the div to remove itself, it will only do so if I hovered over it. If I didn't, the div stays and on next hover it adds another one. If I add on mouse out of the parent element to remove the div, I cannot get to hover over the child div, cause as soon as I leave the parent, the child div is removed. The parent element is an (a href) inside a "TD" in a table. The code goes like this:
<script type="text/javascript">
function PopPanel(ownerElem) {
var myParent = ownerElem.parentNode;
var popanel = document.createElement("div");
popanel.className = "divPopPanel";
popanel.setAttribute("display", "block")
var phoneimg = document.createElement("img");
phoneimg.src = '/images/ImageAdditions/Phone.png';
phoneimg.className = "popupPhone";
popanel.appendChild(phoneimg);
phoneimg.onclick = function () {
try {
location.replace("Mylauncher:\\\\nas\\vol5\\SYSTEM\\ITR\\Scripts\\SomeProgram.exe" + " " + ownerElem.innerText);
}
catch (err) {
}
};
myParent.appendChild(popanel);
popanel.onmouseout = function (e) { this.parentNode.removeChild(this) }; //this removes itself on mouseout.
myParent.onmouseout = function (e) { popanel.parentNode.removeChild(popanel) }; // this removes the child element of the parent (which is the same element as above) on mouse out.
};
Well, after a long and miserable trial and error session, I've figured this out.
First I've modified the code that generates and populates the gridview with data, like this:
VB.net
dt.Columns.Add("InternalPhoneDialer", Type.GetType("System.String"))
Dim rn As New Random
Dim randNum As Integer = rn.Next(12, 428)
Dim internalphone As String = dr("InternalPhone").ToString
If internalphone.Contains(" ") Then
internalphone = internalphone.Substring(0, internalphone.IndexOf(" "))
internalphone = internalphone & randNum.ToString()
Else
internalphone = internalphone & randNum.ToString()
End If
//Substitute the current column with the newly created one above
dr("InternalPhoneDialer") = "<div id='popPanelWrapper" & internalphone & "' onmouseover='PopPanel(" & "popPanelWrapper" & internalphone & ");' onmouseleave='PopPanelClose(" & "popPanelWrapper" & internalphone & ");'> <a class='popPanelLink' href='javascript:void(0);' >" & dr("InternalPhone") & "</a> </div>"
I have made sure that I concatenate a unique id to each div in case the phone number is the same for another column (where I implement the same solution). So I added the column inner content + a random number and concatenated it to the DIV name.
Then, on client side I've modified my script like this:
JavaScript
<script type="text/javascript">
function PopPanel(ownerElem) {
var myParent = ownerElem;
var phoneimgexist = !!document.getElementById("popupPhone");
if (phoneimgexist) {
return
} else {
var phoneimg = document.createElement("img");
phoneimg.src = '/_layouts/15/images/ImageAdditions/Phone.png';
phoneimg.id = "popupPhone";
phoneimg.setAttribute("display", "block")
myParent.appendChild(phoneimg);
}
phoneimg.onclick = function () {
try {
location.replace("launcher:\\\\drive01\\vol1\\SYSTEM\\ITR\\Scripts\\Jabber.exe" + " " + ownerElem.innerText);
}
catch (err) {
}
};
};
function PopPanelClose(ownerElem) {
var myParent = ownerElem;
var phoneimg = document.getElementById("popupPhone");
var phoneimgexist = !!document.getElementById("popupPhone");
if (phoneimgexist) {
phoneimg.parentNode.removeChild(phoneimg);
} else {
return
}
};
Now, on mouse over a GridVew cell that contains a phone number I get an icon. By clicking it I can call the number.
In my opinion this solution is much better suited for the task, instead of creating a hidden div with image and data for every row in what could be thousands of entries in the GridView.
This no doubt saves a lot of resources.
I am trying to animate a dynamically created div with javascript, the id for the div is assigned when it is created, everything works fine until I attempt to animate one of the divs, I am trying this :
function start() // Called from a button click
{
var moveDiv= document.getElementById('Id0'); // Id0 is the Id of the div to move
animate(moveDiv); // Recursive animate
}
function animate(inDiv)
{
inDiv.style.left = parseInt(inDiv.style.left)+1+'px';
setTimeout(animate,20); // Recursive call
}
I know this is supposed to move the div infinitely to the left. However nothing happens at all and I cannot figure out why, I don't think its the fact that I dynamically create the divs as I have checked all the Id's and they all exist so I don't think its because it can't find Id0, but just incase here is a snippet of my div creation code :
for(var i=0; i<ca.length; i++)
{
var c = ca[i].trim();
var start = c.indexOf('"coursename":"') + 14;
var end = c.indexOf('","coursemark":"');
var CC = c.substring(start,end);
var start = c.indexOf('","coursemark":"') + 16;
var end = c.indexOf('%"')+1;
var CM = c.substring(start,end);
var idCount = i;
var div = document.createElement("div");
div.style.width = "180px";
div.style.height = "75px";
div.style.backgroundColor = "rgba(0,100,175,0.8)";
div.style.color = "white";
div.style.marginTop = "2%";
div.style.marginLeft = "50%";
div.id = "sortID"+idCount;
div.innerHTML = "Course Name : " + CC + " Course Mark : " + CM + " Id : " + div.id;
document.body.appendChild(div);
}
This code works fine however and creates the divs perfectly, I just can't get any div to move. Any help would be greatly appreciated.
Couple of problems...
function start() // Called from a button click
{
var moveDiv= document.getElementById('Id0'); // Id0 is the Id of the div to move
animate(moveDiv); // Recursive animate
}
There is no element with ID of Id0. All of your generated element IDs look like sortID...
And then...
function animate(inDiv)
{
inDiv.style.left = parseInt(inDiv.style.left)+1+'px';
setTimeout(animate,20); // Recursive call
}
inDiv.style.left has never been initiated
You're not passing inDiv through to your recursive animate call
So firstly check your element references. Then make sure you're setting the position of the div correctly, or handling scenarios where it isn't yet set. And finally make sure you pass inDiv through recursively.