How to display current time inside a div using JQuery - html

I need to display the current time when I click the button each time, I've achieved the DOM of creating new divs when clicked on button, but I'm not getting the time inside span.
HTML
<button onClick="createDiv()">Record Time</button>
<div id="getText" style="display: none;">
<span id="showTime"></span>
</div>
Script
function createDiv()
{
let div = document.createElement('div');
document.body.appendChild(div);
var now = moment().format("h:mm:ss A");
$('#showTime').append(now);
}
As the code above, current time should be displayed on each new div.

I believe you are using jquery in your script, if so simply replace the
line: $('#showTime').append(now);
with: $('#showTime').text(now);
with vanilla JS you can also do this:
function createDiv(){
let div = document.createElement('div');
document.body.appendChild(div);
var now = moment().format("h:mm:ss A");
let timeNow = document.createTextNode(now);
$('#showTime').append(timeNow);
}

Related

JQuery populate div with link content but also need to move (like anchor link) to area where div located

I have unordered list of links. Using JQuery, when clicked, the link's contents (a div with image and text) are loaded into the section specified. This all works beautifully. But I'm wondering how to also get the onclick function to move the view to the div's location on the page similarly to how anchor tag works. Here is the site where you can see the div being populated, but not moving down to view it. https://www.thecompassconcerts.com/artists.php
My JQuery knowledge is not awesome (I'm being generous).
I followed Osama's suggestion to add event listener and I got almost correct results. Upon first click...contents are loaded but do not move. But on every successive click, it functions perfectly: Contents loaded and move to div (like an anchor link) works! BUT...not on Safari or Mobile Safari.
Here is my jQuery. I assume if first click is not working that I must add listener before the first click?? Can the event listeners be added on page load BEFORE the function to prevent default click, etc.?
<script>
// BEGIN FUNCTION TO CAPTURE AND INSERT CONTENT
$(document).ready(function () {
// PREVENT DEFAULT LINK ACTION
$('.bio').click(function (e) {
e.preventDefault();
// ADD LISTENER TO EACH ITEM BY CLASS
var list = document.getElementsByClassName("bio");
for (let i = 0; i < list.length; i++) {
list[i].onclick = moveToDiv;
}
// FUNCTION TO MOVE TO LOCATION
function moveToDiv() {
document.location = "#performbio";
}
// STORE the page contents
var link = $(this).attr("href");
// load the contents into #performbio div
$('#performbio').load(link);
});
});
</script>
Here is the HTML with links in unordered list
<!-- CONTRIBUTING ARTISTS LIST AND BIOS -->
<section id="artists">
<h2>Contributing Artists</h2>
<ul class="cols">
<li><a class="bio" href="performers/first-last.html">First Last</a></li>
<li><a class="bio" href="performers/first-last.html">First Last</a></li>
<li><a class="bio" href="performers/first-last.html">First Last</a></li>
</ul>
</section>
Here is HTML of Section where code is being inserted by function
<!-- Performer Bios Dynamically updated -->
<section id="performbio">
</section>
Here is div contents that are being inserted
<div class="artistbio">
<p class="artistname">First Last</p>
<img class="artistimg" src="performers/img/name.jpg">
<p>lots of text here</p>
</div>
If I understand it right, you want to scroll to the section where the details appear on clicking any item in the list but through js and not HTML. In that case, you would add an onclick listener on to the list elements like so:
listElement.onclick = moveToDiv;
The function:
function moveToDiv() {
document.location = "#performbio";
}
A simple way to add a listener to all of the elements:
var list = document.getElementsByClassName("bio");
for (let i = 0; i < list.length; i++) {
list[i].onclick = moveToDiv;
}
For the edited post, you need to move the function definition out of the document.ready function. you would change the script to:
// FUNCTION TO MOVE TO LOCATION
function moveToDiv() {
document.location = "#performbio";
}
$(document).ready(function () {
// PREVENT DEFAULT LINK ACTION
$('.bio').click(function (e) {
e.preventDefault();
// ADD LISTENER TO EACH ITEM BY CLASS
var list = document.getElementsByClassName("bio");
for (let i = 0; i < list.length; i++) {
list[i].onclick = moveToDiv;
}
// STORE the page contents
var link = $(this).attr("href");
// load the contents into #performbio div
$('#performbio').load(link);
});
});
Another Solution: Using scrollIntoView
First, get all the elements into a variable using querySelectorAll
var elements = document.querySelectorAll(".bio");
Then create a function, for the scrolling part:
function scroll(element) {
element.scrollIntoView();
}
Then just add the onclick listener:
for (let i = 0; i < elements.length; i++) {
elements[i].addEventListener('click', function() {
scroll(elements[i]);
});
}
I found it very frustrating to try to accomplish these two tasks so instead of a jQuery solution I opted for a CSS solution.
I populated my DIV with all the php includes, gave them unique id's for the anchors to work and then used CSS to hide them by default until clicked and it works like a charm....shows only what I need to show and goes there like an anchor is supposed to.
I must thank Ghost for all of your help and efforts to try and solve this via jQuery. You were very kind and generous.
Here is the code I used:
My collection of links.
<li><a class="bio" href="#artist-name1">Name 1</a></li>
<li><a class="bio" href="#artist-name2">Name 2</a></li>
which anchors to these divs
<div class="bio-container" id="artist-name1">
<?php include('performers/name-lastname.html'); ?>
</div>
<div class="bio-container" id="artist-name2">
<?php include('performers/name-lastname.html'); ?>
</div>
Then I use this CSS to hide those divs until the anchors are clicked.
I'm using [id*="artist-"] to target only links with such text...very easy. Not ideal for a massive list...but mine is not so large so it will do for this situation.
[id*="artist-"] {display: none;}
[id*="artist-"]:target {display: block;}

How to refresh html element after modifying element

I have been trying to print after modifying html element but element has not been changed. (Angular2)
This source code is simplified one.
<div *ngIf="displayType === 'screen'">
<div>This is Screen</div>
</div>
<div *ngIf="displayType === 'print'">
<div>This is Print</div>
</div>
And when click a button the following event.
displayType: string = 'screen'; // default
OnPrint() {
this.displayType = 'print';
let tmp = document.createElement('div');
let el = this.elementRef.nativeElement.cloneNode(true);
tmp.appendChild(el);
let content = tmp.innerHTML;
let frame1 = document.createElement('iframe');
document.body.appendChild(frame1);
let frameDoc = frame1.contentWindow;
frameDoc.document.open();
frameDoc.document.write('<html><body>'+content+'</body></html>');
frameDoc.document.close();
setTimeout(function () {
window.frames["frame1"].focus();
window.frames["frame1"].print();
document.body.removeChild(frame1);
}, 500);
}
But contents are elements before modifying.
How can I refresh elements?
To refresh the elements you need to trigger the change detection.
Here is a very good post about change detection in Angular 2: http://blog.thoughtram.io/angular/2016/02/22/angular-2-change-detection-explained.html
I've created a plunker here to illustrate it:
http://plnkr.co/edit/0ZwkaQ776mKpLYZJogYx?p=preview
<button (click)="OnPrint()">OnPrint</button>
Also you should not modify the DOM elements directly, you should create a component and use a structural directive to display it (here the component has a selector "my-print"):
<my-print *ngIf="isPrint" [iframeSrc]="..."></my-print>

Can I use different styles within one div

I'm using a script to do a mouseover effect with images and also highlighting text in a different color using the getElementById phrase. I understand that an ID can only be used once, and if it needs to be used more than once I should use class. But there is no getElementByClass function. I have 2 areas of type that I want to highlight, one is centered, the other is left justified. Is there a way to use the same id for both styles?
<div id="georgia">
<style="text-align: center;">
<strong>Headquarters:
</strong>
</style>more text here
</div>
This is the script I am using:
<script type="text/javascript">// < ![CDATA[
function on(el) {
if (document.getElementById(el)) {
document.getElementById(el).style.color="green";
};
};
function off(el) {
if (document.getElementById(el)) {
document.getElementById(el).style.color="";
};
};
// ]]></script>
So what you are saying is I can replace the getElementById with getElementByClassName then it will work?
This is the format I'm using, the first part of the text (Headquarters) is not showing up, but the second part (more text here) is fine.
You need to use document.getElementsByClassName, which returns a list of the objects with that class name:
var all = document.getElementsByClassName("bar");
for(var i = 0; i < all.length; i++){
var obj = all[i];
obj.style.fontWeight = 'bold';
}
<div id="foo" class="bar">hi</div>
<div class="bar">bye</div>
<div id="bar">sup</div>

Toggle between two div couples when you click on them

I've found some Javascript code on the web for toggling between two images when clicking on them as in this example.
Now I wonder how to achieve the same result using divs with the pictures being inside the divs.
Both the small and the large image will each be the background image of a div which is inside another div that forms the border (I need to do this to be able to set the inner border radius of the image, which I can when I use an inner div and set its border radius). So I have:
<div class="bordersmallpicture"><div class="smallpicture"></div></div>
and
<div class="borderlargepicture"><div class="largepicture"></div></div>
How can I tell Javascript to toggle between those two div couples instead of images? Here is the Javascript code that I found for the images:
<script>
var imageURL = "small-picture.png";
if (document.images) {
var smallpicture = new Image();
smallpicture.src = "small-picture.png";
var largepicture = new Image();
largepicture.src = "large-picture.png";
}
function changeImage() {
if (document.images) {
if (imageURL == "large-picture.png") {imageURL = "small-picture.png";}
else {imageURL = "large-picture.png";}
document.myimage.src = imageURL;
}
}
</script>
And the HTML part:
<img src="small-picture.png" name="myimage" title="Click to resize" alt="tree">
Can anyone give me a hint how to edit this code to toggle between the div couples mentioned above? Or will a whole new code be necessary when dealing with divs?
You simply need to toggle the classes. See a running example using your images as CSS background in the classes:
<div id="border-div" class="bordersmallpicture">
<div id="image-div" class="smallpicture"></div>
</div>
The the Javascript becomes:
<script>
function changeImage() {
var currentClass = document.getElementById('border-div').className;
if(currentClass == 'borderlargepicture') {
document.getElementById('border-div').className = 'bordersmallpicture';
document.getElementById('image-div').className = 'smallpicture';
} else {
document.getElementById('border-div').className = 'borderlargepicture';
document.getElementById('image-div').className = 'largepicture';
}
}
</script>
If you expect using javascript a lot, I recommend using jQuery which would make the code easier:
<script>
function changeImage() {
$('#border-div').toggleClass('bordersmallpicture').toggleClass('borderlargepicture');
$('#image-div').toggleClass('smallpicture').toggleClass('largepicture');
}
</script>
toggleClass turns ON/OFF a class (Here is the example)

Create div and add style

I have one big div with id="elements" and I load from JSON file new elements objects and I need that for every element create new div inside elements ( elements div should contain lot off smaller divs, for every element one small div ). How to place this small divs inside this big div one behind another ? How to add this small divs a class style ?
In Dojo (since you have the dojo tag):
var div_elements = dojo.byId("elements");
dojo.forEach(json_data.items, function(item) {
dojo.create("div", { "class":"whatever " + item.classNames }, div_elements);
});
Of course, you can put anything as the class for your div. I just provided an example. In the second argument to dojo.create, you pass in a hash containing all the properties you want that div to have.
Create a new DOM element like so:
var childDiv = document.createElement('div');
Then add to the outer div like so:
var insertedElement = div.insertBefore(childDiv, null);
You would then keep creating childDivs as you iterate over your JSON data, and inserting them into the div Node as above.
I think you need something like this:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js" ></script>
<script type="text/javascript">
$(document).ready(function(){
json_data = 'Hey';
$('#elements').append('<div class="in_elements">' + json_data + '</div>');
});
</script>
<div id="elements">
</div>
Test it
There a simple jQuery functions for that:
var box= $("#elements");
// create elements
for (var i=0; i<items.length; i++) {
var t = $("<div class=\"element\" id=\"item_"+i+"\">"+items[i]['text']+"</div>");
box.append(t);
}
That's what you where looking for?