I have sliders which gives user chance to choose time range . Based on this time range some messages printed in the screen with some style. I am kinda generating style for those messages between following tags.
<section> .... </section>
When I change my slider values which determines the range of the new messages, the new ones come behind old messages. I just want the all messages from the new range not old one .
You can see jsFiddle of my code also here
$(function() {
$( "#slider-5" ).slider({
range:true,
min: parseInt(ctime[0]),
max: parseInt(ctime[ctime.length-1]),
values: [ parseInt(ctime[4]),parseInt(ctime[len])],
change: function( event, ui ) {
$( "#slidevalue" )
.val( formatDateTime(ui.values[ 0 ]) + " - " + formatDateTime(ui.values[ 1 ]) );
new_var=ui.values[0];
var body = document.getElementsByTagName('body')[0];
var section = document.createElement('section');
section.id = 'cd-timeline';
section.className = 'cd-container';
body.appendChild(section);
for (var x=0;parseInt(ctime[x])<ui.values[0];x++);
for (var x = 0;parseInt(ctime[x])<=ui.values[1]; x++) {
var datum = new Date(parseInt(ctime[x]));
var outerDiv = document.createElement('div');
outerDiv.className = 'cd-timeline-block';
section.appendChild(outerDiv);
var div = document.createElement('div');
div.className = 'cd-timeline-img cd-location';
outerDiv.appendChild(div);
var img = document.createElement('img');
img.src = 'img/cd-icon-location.svg';
img.setAttribute('alt', 'Location');
div.appendChild(img);
var div = document.createElement('div');
div.className = 'cd-timeline-content';
outerDiv.appendChild(div);
var h2 = document.createElement('h2');
div.appendChild(h2);
h2_text = document.createTextNode('foo');
h2.appendChild(h2_text);
var p = document.createElement('p');
div.appendChild(p);
p_text = document.createTextNode(<?php echo json_encode($content); ?>[x]);
p.appendChild(p_text);
var span = document.createElement('span');
span.className = 'cd-date';
div.appendChild(span);
span_text = document.createTextNode(formatDateTime(datum));
span.appendChild(span_text);
}
}
});
});
If i understood correctly, (it appears to be correct from comments) You don't need to append new <section> every time the slider is changed (If you're doing this note that you can't use the same id for multiple elements).
Have the <section> in HTML, like
<section id="cd-timeline" class="cd-container"></section>
then you can replace it's content using $('#cd-timeline').html(); as follows:
$(function() {
$( "#slider-5" ).slider({
range:true,
min: parseInt(ctime[0]),
max: parseInt(ctime[ctime.length-1]),
values: [ parseInt(ctime[4]),parseInt(ctime[len])],
change: function( event, ui ) {
$( "#slidevalue" )
.val( formatDateTime(ui.values[ 0 ]) + " - " + formatDateTime(ui.values[ 1 ]) );
new_var=ui.values[0];
for (var x=0;parseInt(ctime[x])<ui.values[0];x++);
for (var x = 0;parseInt(ctime[x])<=ui.values[1]; x++) {
var datum = new Date(parseInt(ctime[x]));
var outerDiv = document.createElement('div');
outerDiv.className = 'cd-timeline-block';
$('#cd-timeline').html(outerDiv); // replace the content of existing section
var div = document.createElement('div');
div.className = 'cd-timeline-img cd-location';
outerDiv.appendChild(div);
var img = document.createElement('img');
img.src = 'img/cd-icon-location.svg';
img.setAttribute('alt', 'Location');
div.appendChild(img);
var div = document.createElement('div');
div.className = 'cd-timeline-content';
outerDiv.appendChild(div);
var h2 = document.createElement('h2');
div.appendChild(h2);
h2_text = document.createTextNode('foo');
h2.appendChild(h2_text);
var p = document.createElement('p');
div.appendChild(p);
p_text = document.createTextNode(<?php echo json_encode($content); ?>[x]);
p.appendChild(p_text);
var span = document.createElement('span');
span.className = 'cd-date';
div.appendChild(span);
span_text = document.createTextNode(formatDateTime(datum));
span.appendChild(span_text);
}
}
});
});
How to remove the section: $("section").remove();
How to remove its children: $("section").children().remove();
Before appending child elements to the 'section' you can say
$('section').children().remove();
to get rid of everything within the 'section'
This will take everything inside of your section and remove it. Be careful though. If you have other elements within your section already, those will be removed too. If you want to avoid that. Put your content that will be added and the stuff to be removed inside of an element that is seperate from the other content.
Like this
<section>
<div>
//all your other content
</div>
<div id='sliderContent'>
//all your slider content
</div>
</section>
Then in your jquery use instead
$('section #sliderContent').children().remove();
This will make it so you do not have to append a section to the dom anymore
Related
Ok,for testing purposes lets say i have a function where it appends <li> elements inside an <ol>
container,and i want to keep all list items i've added,is there a way to store them in Local Storage (or any other way,locally) so i can retrieve them every time i reload the page ?
I've studied a little bit in Window.localStorage api,i did'nt find a method to store a dynamic element like that,but again if there is something i would'nt know to recognize the right practice to do it,since i'm still a student.Any ideas?
var textcounter = 1;
var inputcounter = 1;
function addText() {
var div = document.getElementById("div");
var texttobestored =document.createElement("li");
texttobestored.id = "text" + textcounter;
texttobestored.style.color="red";
texttobestored.innerHTML = "<p>I WANT TO KEEP THIS TEXT</p>";
div.appendChild(texttobestored);
textcounter++;
}
function addInputs() {
var div = document.getElementById("div");
var inputstobestored =document.createElement("li");
inputstobestored.id = "input" + inputcounter;
inputstobestored.innerHTML = "<input placeholder = ContentsToBeSaved>";
inputstobestored.style.color = "blue";
inputstobestored.style.width = "600px";
div.appendChild(inputstobestored);
inputcounter++;
}
#div{
width:600px;
}
<html>
<body>
<ol id="div">
<button onclick="addText()" style="height:100px;width:100px">ADD TEXT</button>
<button onclick="addInputs()" style="height:100px;width:100px">ADD INPUTS</button>
</ol>
</body>
</html>
Here is a working fiddle: https://jsfiddle.net/3ez4pq2d/
This function calls saveInput to save the data to localstorage. Then it also generates the
inputs that are saved via loadInput.
This just stores the ID, COLOR and WIDTH. But using this as a base you can save additional fields also.
function saveinput(obj) {
saved = localStorage.getItem("items") || "[]"
saved = JSON.parse(saved)
saved.push(obj)
localStorage.setItem("items", JSON.stringify(saved))
}
var textcounter = 1;
var inputcounter = 1;
function addText() {
var div = document.getElementById("div");
var texttobestored = document.createElement("li");
texttobestored.id = "text" + textcounter;
texttobestored.style.color = "red";
texttobestored.innerHTML = "<p>I WANT TO KEEP THIS TEXT</p>";
div.appendChild(texttobestored);
textcounter++;
}
function addInputs() {
var div = document.getElementById("div");
var inputstobestored = document.createElement("li");
inputstobestored.id = "input" + inputcounter;
inputstobestored.innerHTML = "<input placeholder = ContentsToBeSaved>";
inputstobestored.style.color = "blue";
inputstobestored.style.width = "600px";
saveinput({
id: "input" + inputcounter,
color: "blue",
width: "600px"
})
div.appendChild(inputstobestored);
inputcounter++;
}
function loadInput() {
inputs = localStorage.getItem("items") || "[]"
inputs = JSON.parse(inputs)
inputs.forEach(function(input) {
var div = document.getElementById("div");
var inputstobestored = document.createElement("li");
inputstobestored.id = input.id;
inputstobestored.innerHTML = "<input placeholder = ContentsToBeSaved>";
inputstobestored.style.color = input.color;
inputstobestored.style.width = input.width;
div.appendChild(inputstobestored);
inputcounter++;
})
}
loadInput();
I'm trying to make a container div for each image and its description at each iteration in my for loop, but JQuery is lumping all the image divs and description divs together into one container div, and that's messing up the whole layout.
I'm not sure why it's doing that, especially since I'm creating a new container div and appending to it within the for loop.
Here's the JSFiddle: https://jsfiddle.net/ZEZEME/wza7q3tn/4/
HTML
<div class=PgTwo></div>
JS
$.getJSON(url, function(data) {
arr = data.data;
for (var i = 0; i < arr.length; i++) {
var articleInfo = arr[i];
console.log(articleInfo);
var imgURL = articleInfo["listingimage"]['url'];
var title = articleInfo["title"];
var desc = articleInfo["listingdescription"];
if (imgURL != "") {
var imgWrapperDiv = document.createElement('div');
var imgDiv = document.createElement('div');
var descDiv = document.createElement('div');
imgDiv.id = 'imgDiv';
imgWrapperDiv.id = 'imgWrapperDiv';
descDiv.id = 'descDiv';
descDiv.textContent = desc;
var imgurlCSS = 'url("'+imgURL+'")';
$(imgDiv).css({'background-image': imgurlCSS, 'background-repeat': 'no-repeat', 'background-size': 'cover'});
$(imgDiv).append($('<a href="" id=link >'+ title +'</a>').css('text-decoration', 'none'));
$('#imgWrapperDiv').append(imgDiv);
$('#imgWrapperDiv').append(descDiv);
$('.PgTwo').append(imgWrapperDiv);
}
}
});
You're only using one id in the for loop. So you're creating the wrapper div, then setting its id but every time it sets it to the same id as before. In the DOM only one wrapper div is present then.
I'm confused on how to change text content of div with the DOM. When event is triggered, I see that the new text replace the old but it is in a new div. I want to keep it in "transcriptText" to keep all attributes.`How can I do that?
This is my old div with text inside:
var transcriptText = document.getElementById("transcriptText");
these are my new text SPAN elements
var newTranscript = document.createElement("div");
This is how I handle the event
function EventHandler() {
transcriptText.parentNode.replaceChild(newTranscript, transcriptText);
}
Here is the JSFiddle on how it currently works:
http://jsfiddle.net/b94DG/
What you're doing now is creating a new div, newTranscript, which you create by appending a bunch of spans based on the old text. Then in your event handler you replace the old one with the new one. Instead of that, you could still copy the text from the old one, but then clear it and append the children on the old div, replacing line 36 with:
transcriptText.appendChild(newSpan);
To clear the old element, it might work to just set innerHTML to "", or if necessary you could remove all the children with removeChild as described at https://developer.mozilla.org/en-US/docs/Web/API/Node.removeChild
EDIT:
I modified your fiddle to reflect this:
http://jsfiddle.net/b94DG/1/
You can change the innerHTML of transcriptText instead of creating a new div.
var transcriptText = document.getElementById("transcriptText");
var divideTranscript = document.getElementById("divideTranscript");
divideTranscript.onclick = function() {
var sArr = transcriptText.innerHTML.split(" ");
var newInnerHTML = "";
for (var i = 0; i < sArr.length; i++) {
var item = sArr[i];
var newText = "<span class='highlight' id='word" + i + "'>" + item + " </span>";
newInnerHTML += newText;
}
transcriptText.innerHTML = newInnerHTML;
var mouseOverFunction = function () {
this.style.backgroundColor = 'yellow';
};
var mouseOutFunction = function () {
this.style.backgroundColor = '';
};
var highlight = document.getElementsByClassName("highlight");
for (i = 0; i < highlight.length; i++) {
highlight[i].onmouseover = mouseOverFunction;
highlight[i].onmouseout = mouseOutFunction;
}
};
Here's the fiddle: http://jsfiddle.net/khnGN/
I am creating dynamically multiple div elements using JavaScript. Below is the code I have used:
for(i=0;i<3;i++)
{
var d1 = document.createElement('div');
d1.id = "div" + i;
var l1 = document.createElement('label');
l1.innerHtml = "Hello";
d1.appendChild(l1);
var line1 = document.createElement('hr');
d1.appendChild(line1);
document.body.appendChild(d1);
}
Output:
Hello
Hello
Hello
Now I want to dynamically append event say onmouseover and onmouseout so that whenever I move cursor over a particular div element say div1, div2 or div3, that respective div section should change color (say blue) and when cursor moves out it should return to its original color.
I have tried working out but I am unable to retrieve the div id's which I have created dynamically.
You don't need to select by ID. You already have the element, so go ahead and add handlers to it.
for(i=0;i<3;i++) {
var d1 = document.createElement('div');
d1.id = "div" + i;
var l1 = document.createElement('label');
l1.innerHtml = "Hello";
d1.appendChild(l1);
var line1 = document.createElement('hr');
d1.appendChild(line1);
document.body.appendChild(d1);
d1.onmouseover = function() {
this.style.color = "#00F";
};
d1.onmouseout = function() {
this.style.color = "";
};
}
Just build your handlers and then assign them in the loop:
var mouseover = function() {
this.style.backgroundColor = '#AAF';
},
mouseout = function() {
this.style.backgroundColor = '';
};
for (i = 0; i < 3; i++) {
var d1 = document.createElement('div'),
l1 = document.createElement('label'),
line1 = document.createElement('hr');
d1.id = "div" + i;
l1.innerHtml = "Hello";
d1.appendChild(l1);
d1.appendChild(line1);
d1.onmouseover = mouseover;
d1.onmouseout = mouseout;
document.body.appendChild(d1);
}
Demo at: http://jsfiddle.net/vfVCm/
If your elements are created dynamically it may be better to use event delegation and attach the event listener to the parent element instead of every element that you're dynamically creating. This way your listener will work even for elements created after it's attached. DOM events bubble, and an actual target of an event is available as event.target. Here is an example:
<div id="parent">
<p id="event1">A</p>
<p id="event2">B</p>
<p id="event3">C</p>
</div>
// call on DOMContentLoaded
document.getElementById("parent").addEventListener("click", function(e) {
if(e.target && e.target.nodeName.toLowerCase() == "p") {
alert("Clicked element " + e.target.id);
}
});
See jsfiddle.
for(var i=0; i<myJSONObject.model.length; i++){
var create_div = document.createElement('div');
create_div.id = 'model_id'+i;
create_div.innerHTML = myJSONObject.model[i].model_name;
var assign_innerHTML = create_div.innerHTML;
var create_anchor = document.createElement('a');
document.getElementById('models').appendChild(create_div);
document.getElementById(create_div.id).appendChild(create_anchor);
}
for ex the myJSONObject.model.length is 2
the output is like this
<div id = 'model_id0'>XXXXX<a> </a></div>
<div id = 'model_id1'>XXXXX<a> </a></div> */
but instead of above the output sholud be like this
<div id = model_id0> <a> xxxxxx</a></div>
<div id = model_id1> <a> xxxxxx</a></div>
how to append it inside of the innerhtml
any one plz reply !!!!
two suggestions:
1.) instead of assigning innerHTML to model_idx div assign the model name to its child a. and 2nd instead of appending it to DOM in every loop do it after completing the loop as to minimize frequent the DOM Update ie by:
objContainer = document.createElement('div');
for(....)
{
var create_div = document.createElement('div');
create_div.id = 'model_id'+i;
var create_anchor = document.createElement('a');
create_anchor.innerHTML = myJSONObject.model[i].model_name;
create_div.appendChild(create_anchor);
objContainer.appendChild(create_div);
}
document.getElementById('models').appendChild(objContainer);
I would go along the lines of:
var i = 0,
m = myJSONObject.model,
l = m.length,
models = document.getElementById("models");
for(; i < j; i++) {
var model = m[i];
var create_div = document.createElement("div");
create_div.id = "model_id" + i;
create_div.innerHTML = "<a>" + model.model_name + "</a>";
models.appendChild(create_div);
}
Unless you specifically need to do something to the anchor itself (other than set its innerHTML), there's no need to create a reference to an element for it. If you do need to do something specific to that anchor, then in that case have this, instead:
EDIT: As per your comment, you DO want to do something to the anchor, so go with this (now updated) option - assuming the anchor will always be a child of the div that has the ID you require. The reason "model_id" + i is being put in as a string is because that is exactly what is being passed into the HTML - the document has no clue what "i" is outside of javascript:
var i = 0,
m = myJSONObject.model,
l = m.length,
models = document.getElementById("models");
for(; i < j; i++) {
var model = m[i];
var create_div = document.createElement("div");
var create_anchor = document.createElement("a");
create_div.id = "model_id" + i;
create_anchor.innerHTML = model.model_name;
if(window.addEventListener) {
create_anchor.addEventListener("click", function() {
getModelData(1, this.parentNode.id);
}, false);
} else {
create_anchor.attachEvent("onclick", function() {
getModelData(1, this.parentNode.id);
});
}
create_div.appendChild(create_anchor);
models.appendChild(create_div);
}