function showHome() {
removeSlideShow();
var homeHeader = document.createElement("div");
homeHeader.setAttribute("id", "homeHeader");
document.getElementById("window").insertBefore(homeHeader, document.getElementById("content"));
var slideShowDiv = document.createElement("div");
var images = ["slideShow/slideShow-1.jpg", "slideShow/slideShow-2.jpg", "slideShow/slideShow-3.jpg", "slideShow/slideShow-4.jpg", "slideShow/slideShow-5.jpg", "slideShow/slideShow-6.jpg", "slideShow/slideShow-7.jpg"];
homeHeader.appendChild(slideShowDiv);
startSlideShow(slideShowDiv, images);
content.innerHTML = "";
}
function startSlideShow(element, images) {
var iterator = 0;
element.setAttribute("id", "slideShowDiv");
element.setAttribute("style", "background-image: url(" + images[0] + ")");
var startInterval = setInterval(function() {
iterator++;
if (iterator == images.length) iterator = 0;
element.setAttribute("style", "background-image: url(" + images[iterator] + ")");
element.style = "background-image: url(" + images[iterator] + ")";
transition(element);
}, 3000);
}
function removeSlideShow() {
if (document.getElementById("homeHeader")) {
document.getElementById("window").removeChild(document.getElementById("homeHeader"));
}
}
function transition(element) {
element.setAttribute("style", "opacity:0.01;");
var i = 0;
var set = setInterval(function() {
i += 0.01;
element.setAttribute("style", "opacity:" + i + ";");
}, 4);
setTimeout(function() {
clearInterval(set);
element.setAttribute("style", "opacity:1;");
}, 500);
}
div#homeHeader {
background-color: #FFF;
width: 900px;
height: 280px;
border: solid 2px #F00;
border-radius: 20px;
}
div#slideShowDiv {
background-image: url(slideShow/slideShow-1.jpg);
background-color: #FFF;
width: 898px;
height: 278px;
border: solid 1px #FFF;
border-radius: 20px;
background-size: 100% 100%;
}
What i want to do is change the background image every 3 seconds. The code work but it's not changing the image, stays at 'slideShow-1.jpg'. If i remove the transition(element); part, the image rotate just fine. What should i do to get it work? Im still beginner in Javascript, will learn jquery when i got better. Sorry for my grammar.
If i remove the transition(element); part, the image rotate just fine.
The transition part sets a new value for the style attribute.
Setting a new value for the attribute replaces the old value.
You are removing the style for the background image. (So the one from the stylesheet is applied again instead).
What should i do to get it work?
Don't use setAttribute(..., ...) to modify styles.
Use .style.cssPropertyName = ... instead.
Related
I'm trying to create a small and interactive image gallery inside my page and everything besides this problem is working fine: When I mouse over the images they change opacity and size, as expected, however, after I click one of them and enlarge it, nothing happens when I try mousing over them again.
This is what I mean:
Current CSS:
#houseImages img {
opacity: 0.7;
margin: 1em;
transition: 0.3s;
width: 18em;
height: 15em;
border-radius: 3em;
border-style: solid;
border-width: 0.05em;
}
#houseImages img:hover {
transform: scale(1.1);
opacity: 1.0;
cursor: pointer;
}
Current script that is being used when an image is clicked:
"use strict";
function defaultSettings(imgElement)
{
imgElement.style.position = "initial";
imgElement.style.transform = "scale(1.0)";
imgElement.style.opacity = "0.7";
}
function clickedSettings(imgElement)
{
imgElement.style.position = "absolute";
imgElement.style.transform = "scale(2.6)";
imgElement.style.left = "40%";
imgElement.style.top = "30%";
imgElement.style.opacity = "1.0";
imgElement.style.zIndex = "99";
}
function imageClicked(imgID)
{
let img = document.getElementById("img" + imgID);
let otherImages = document.querySelectorAll("#houseImages img:not(#img" + imgID + ")");
let div = document.getElementById("houseImages");
let previousCloseImageButton = document.querySelector("#houseImages button");
// if another image was already clicked there's some cleanup to do
if(previousCloseImageButton)
previousCloseImageButton.remove();
otherImages.forEach(image => defaultSettings(image));
clickedSettings(img);
let closeImageButton = document.createElement('button');
closeImageButton.setAttribute("id","close");
closeImageButton.setAttribute("onclick","notClicked(" + imgID + ")");
closeImageButton.innerHTML = 'X';
div.append(closeImageButton);
}
function notClicked(imgID)
{
let img = document.getElementById("img" + imgID);
let closeImageButton = document.querySelector("#houseImages button");
defaultSettings(img);
closeImageButton.remove();
}
When you call defaultSettings(img); in the notClicked(imgID) function, you are setting a style property directly on the HTML img objects, as if you have written <img style="opacity: 0.7"> in HTML. Styles set on an object always have higher priority than those resulting from a stylesheet. In effect, rules defined for #houseImages img:hover cannot affect your image.
What you need to do is unset a local style property to let the stylesheet work again:
function defaultSettings(imgElement)
{
imgElement.style.position = "";
imgElement.style.transform = "";
imgElement.style.opacity = "";
}
I have created a grid with div, class and id. I want to randomly create a yellow square and I want to assign an id= 'yellowSquare' how do I do it?
var grid = document.getElementById("grid-box");
for (var i = 1; i <= 100; i++) {
var square = document.createElement("div");
square.className = 'square';
square.id = 'square' + i;
grid.appendChild(square);
}
var playerOne = [];
while (playerOne.length < 1) {
var randomIndex = parseInt(99 * Math.random());
if (playerOne.indexOf(randomIndex) === -1) {
playerOne.push(randomIndex);
var drawPone = document.getElementById('square' + randomIndex);
drawPone.style.backgroundColor = 'yellow';
}
}
#grid-box {
width: 400px;
height: 400px;
margin: 0 auto;
font-size: 0;
position: relative;
}
#grid-box>div.square {
font-size: 1rem;
vertical-align: top;
display: inline-block;
width: 10%;
height: 10%;
box-sizing: border-box;
border: 1px solid #000;
}
<div id="grid-box"></div>
I am new to Javascript / jQuery. Any help will be much appreciated ! Thank you
There are two options to your question. You can either change the id of the yellow square which is already created from your code, or create a child element within the square, which looks the same as your current solution. Creating a new child element will let you keep the numeric id pattern for the grid:
Changing the ID :
var element = document.getElementById('square' + randomIndex)
element.id = "yellowSquare";
Adding new element inside:
var node = document.createElement("DIV");
node.id = "yellowSquare";
node.style = "background-color:yellow;height:100%;width:100%;";
var element = document.getElementById('square' + randomIndex)
element.appendChild(node);
I set the styling of the div child to 100% width and height, as it has no content, and would get 0 values if nothing was specified. This should make it fill the parent container.
There are also multiple other ways to achieve the same result, for instance with JQuery.
Use the HTMLElement method setAttribute (source);
...
var drawPone = document.getElementById('square' + randomIndex);
drawPone.style.backgroundColor = 'yellow';
drawPone.setAttribute('id', 'yellowSquare');
...
As you requested in your comment how to move the square i made an example how you can move it left and right using jQuery next() and prev() functions. However because your html elements are 1 dimensional it's not easy to move them up/down and check the sides for collisions. Better would be to create your html table like with rows and columns and this way create a 2 dimensional play field.
Also added a yellowSquery class for selection with $drawPone.addClass('yellowSquare');.
Also since you like to use jQuery I changed your existing code to jQuery function. Might help you learn the framework.
var $grid = $("#grid-box");
for (var i = 1; i <= 100; i++) {
var $square = $("<div>");
$square.addClass('square');
$square.attr('id','square' + i);
$grid.append($square);
}
var playerOne = [];
while (playerOne.length < 1) {
var randomIndex = parseInt(99 * Math.random());
if (playerOne.indexOf(randomIndex) === -1) {
playerOne.push(randomIndex);
var $drawPone = $('#square' + randomIndex);
$drawPone.addClass('yellowSquare');
}
}
$('#button_right').on('click', function(){
$yellowSquare = $('.yellowSquare')
$yellowSquareNext = $yellowSquare.next();
$yellowSquare.removeClass('yellowSquare');
$yellowSquareNext.addClass('yellowSquare');
});
$('#button_left').on('click', function(){
$yellowSquare = $('.yellowSquare')
$yellowSquarePrev = $yellowSquare.prev();
$yellowSquare.removeClass('yellowSquare');
$yellowSquarePrev.addClass('yellowSquare');
});
#grid-box {
width: 400px;
height: 400px;
margin: 0 auto;
font-size: 0;
position: relative;
}
#grid-box>div.square {
font-size: 1rem;
vertical-align: top;
display: inline-block;
width: 10%;
height: 10%;
box-sizing: border-box;
border: 1px solid #000;
}
.yellowSquare {
background-color: yellow;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="grid-box"></div>
<button id="button_left">left</button>
<button id="button_right">right</button><br>
I'm a complete newbie in javascript.
I make a function, that adds a div with id="test_div". After call it creates div in body and give an id to the element. After that i try to write style "element.style.position" and it doesn't work. But i can write a style in this element through "element.style.cssText". I tried to solve this by adding a variable with "window.getElementById()" after create the element, but it also doesn't work.
I don't understand what i am doing wrong. Hope for your help. Thank you.
Sorry for bad English.
html file:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script type="text/javascript" src="test.js">
</script>
</head>
<body>
<button onclick="add('Clicked ', 0)">Click</button>
</body>
</html>
js file:
var element_id = "test_div";
var default_timeout = 3;
var element_bg_color = "rgba(0, 0, 0, .5)";
var element_font_color = "#fff";
var element_pointer_events = "none";
var element_position = "fixed";
var element_top = "0";
var element_left = "0";
var element_padding = '.3em .6em';
var element_margin = "0";
var element_border_radius = "0 0 5px 0";
var add = function(string, timeout){
if(typeof(timeout) === 'undefined'){
timeout = default_timeout;
}
var element = document.createElement('div');
element.id = element_id;
element.style.position = "fixed";
element.style.cssText = "top: 0; left: 0; background-color: " + element_bg_color + "; margin: 0; padding: .3em .6em; border-radius: 0 0 5px 0; color: " + element_font_color + "; pointer-events: " + element_pointer_events + ";";
element.innerHTML = string;
if(document.getElementById(element_id) === null){
document.body.appendChild(element);
}else{
document.body.removeChild(element);
document.body.appendChild(element);
}
if(timeout > 0){
timeout *= 1000;
setTimeout(function() {
document.body.removeChild(element);
}, timeout);
}
};
By setting the cssText you are overwriting all the other styles
As the below example shows even though I set the fontSize to 90px, the span actually gets the font-size and font-weight set in the cssText property.
var span = document.querySelector("span");
span.style.fontSize = "90px";
span.style.cssText = "font-size:20px; font-weight:bold;";
<span>Some Text</span>
So either set each style property separately or set cssText first
Those two lines:
element.style.position = "fixed";
element.style.cssText = "top: 0; left: 0; background-color: " + element_bg_color + "; margin: 0; padding: .3em .6em; border-radius: 0 0 5px 0; color: " + element_font_color + "; pointer-events: " + element_pointer_events + ";";
Switch them.
Explanation:
element.style.position = "fixed";
This line adds position: fixed; to the style attribute of element. So your element looks like
<div id="test_div" style="position: fixed;"></div>
And then:
element.style.cssText = "top: 0; left: 0; background-color: " + element_bg_color + "; margin: 0; padding: .3em .6em; border-radius: 0 0 5px 0; color: " + element_font_color + "; pointer-events: " + element_pointer_events + ";";
This lines replaces the entire style attribute with whatever comes after the = sign.
So your element looks like this:
<div id="test_div" style="/* lots of things here, but NOT "position: fixed;" anymore */"></div>
And here's a fiddle because why not?: http://jsfiddle.net/kxqgr913/
Here is a short snippet jsfiddle.net/nffubk14/ to explain how to add a div, append a text node to it and give it a style, hope this helps you understand what's going on. For more reading on this subject learn about DOM (Document Object Model)
I am trying to create this shape using dynamically created divs. I have this code already in place:
var bgImg = ['ScreenShot.png', 'stars.jpg', 'ScreenShot.png', 'stars_1230_600x450.jpg'];
for (var i = 0, n = 12; i < n; i++) {
var port = document.createElement('div');
document.body.appendChild(port);
port.style.backgroundImage = "url('" + bgImg[3] + "')";
I would like to create this image: https://flic.kr/p/mSJm6G
which will eventually hold images from the array. (one image per slot on the grid.)
I have tried below, which only does not work, it doesn't do what i want, which is to add that amount each time a new div is created. I want a new object to raise by 40px each time it is created.
$(port).css('top','+=40n');
I think that i will have to create three divs/scripts,, one for each row, so that i can get the divs to align properly. the master css will set the divs with a negative margin-top so they can cascade properly.
for reference, my css looks like this:
div {
height: 190px;
width:230px;
background: red;
position: relative;
background: #ef4c4d;
background-position: center;
float: left;
margin: 8px;
top: 30px;
left: 10px;
}
div:before {
content: '';
position: absolute;
bottom: 0; right: 0;
border-bottom: 60px solid #0d1036;
border-left: 60px solid transparent;
width: 0;
}
div:after {
content: '';
position: absolute;
top: 0; left: 0;
border-top: 60px solid #0d1036;
border-right:60px solid transparent;
width: 0;
}
I think that i need to pull the integer from an array, but really not sure.
Some things I notice in your code:
for (var i = 0, n = 12; i < n; i++) {
var port = document.createElement('div');
document.body.appendChild(port);
// <- end "}" of for loop is missing here
port.style.backgroundImage = "url('" + bgImg[3] + "')"; // <- will just be applied on the last created div
I guess you want something like this:
for (var i = 0, n = 12; i < n; i++) {
var port = document.createElement('div');
port.style.backgroundImage = "url('" + bgImg[3] + "')";
document.body.appendChild(port);
}
To update the "top" property, you can use this code with jQuery:
for (var i = 0, n = 12; i < n; i++) {
var port = $('<div></div>');
port.css("background-image", "url('" + bgImg[3] + "')");
port.css("top": 40 * i + "px"); // <- set "top" +40px for each div
$("body").append(port);
}
I'm using the PDF.js library to render a pdf into the canvas. That pdf has hyperlinks in there, The PDF.js library is drawing the pdf into the canvas but the hyperlinks don't work.
Any Idea if it possible that hyperlinks work into the canvas?
Thanks
Here is a fiddle that shows you how to enable annotations (including hyperlinks) in PDF files.
The original PDF file used in the fiddle is here.
I used viewer code (web/page_view.js,web/viewer.css) as refrence to write this fiddle.
HTML:
<!doctype html>
<html lang="en">
<head>
<link href="style.css" rel="stylesheet" media="screen" />
<script src="http://code.jquery.com/jquery-2.0.3.min.js"></script>
<script src="http://seikichi.github.io/tmp/PDFJS.0.8.715/pdf.min.js" type="text/javascript"></script>
<script src="http://seikichi.github.io/tmp/PDFJS.0.8.715/ui_utils.js"></script>
<script src="./main.js" type="text/javascript"></script>
</head>
<body>
<div id="pdfContainer" class="pdf-content">
<canvas id="the-canvas"></canvas>
<div class="annotationLayer"></div>
</div>
</body>
</html>
CSS:
body {
font-family: arial, verdana, sans-serif;
}
.pdf-content {
border: 1px solid #000000;
}
.annotationLayer > a {
display: block;
position: absolute;
}
.annotationLayer > a:hover {
opacity: 0.2;
background: #ff0;
box-shadow: 0px 2px 10px #ff0;
}
.annotText > div {
z-index: 200;
position: absolute;
padding: 0.6em;
max-width: 20em;
background-color: #FFFF99;
box-shadow: 0px 2px 10px #333;
border-radius: 7px;
}
.annotText > img {
position: absolute;
opacity: 0.6;
}
.annotText > img:hover {
opacity: 1;
}
.annotText > div > h1 {
font-size: 1.2em;
border-bottom: 1px solid #000000;
margin: 0px;
}
JavaScript:
PDFJS.workerSrc = 'http://seikichi.github.io/tmp/PDFJS.0.8.715/pdf.min.worker.js';
$(function () {
var pdfData = loadPDFData();
PDFJS.getDocument(pdfData).then(function (pdf) {
return pdf.getPage(1);
}).then(function (page) {
var scale = 1;
var viewport = page.getViewport(scale);
var $canvas = $('#the-canvas');
var canvas = $canvas.get(0);
var context = canvas.getContext("2d");
canvas.height = viewport.height;
canvas.width = viewport.width;
var $pdfContainer = $("#pdfContainer");
$pdfContainer.css("height", canvas.height + "px")
.css("width", canvas.width + "px");
var renderContext = {
canvasContext: context,
viewport: viewport
};
page.render(renderContext);
setupAnnotations(page, viewport, canvas, $('.annotationLayer'));
});
function setupAnnotations(page, viewport, canvas, $annotationLayerDiv) {
var canvasOffset = $(canvas).offset();
var promise = page.getAnnotations().then(function (annotationsData) {
viewport = viewport.clone({
dontFlip: true
});
for (var i = 0; i < annotationsData.length; i++) {
var data = annotationsData[i];
var annotation = PDFJS.Annotation.fromData(data);
if (!annotation || !annotation.hasHtml()) {
continue;
}
var element = annotation.getHtmlElement(page.commonObjs);
data = annotation.getData();
var rect = data.rect;
var view = page.view;
rect = PDFJS.Util.normalizeRect([
rect[0],
view[3] - rect[1] + view[1],
rect[2],
view[3] - rect[3] + view[1]]);
element.style.left = (canvasOffset.left + rect[0]) + 'px';
element.style.top = (canvasOffset.top + rect[1]) + 'px';
element.style.position = 'absolute';
var transform = viewport.transform;
var transformStr = 'matrix(' + transform.join(',') + ')';
CustomStyle.setProp('transform', element, transformStr);
var transformOriginStr = -rect[0] + 'px ' + -rect[1] + 'px';
CustomStyle.setProp('transformOrigin', element, transformOriginStr);
if (data.subtype === 'Link' && !data.url) {
// In this example, I do not handle the `Link` annotations without url.
// If you want to handle those annotations, see `web/page_view.js`.
continue;
}
$annotationLayerDiv.append(element);
}
});
return promise;
}
});
function loadPDFData() {
/*jshint multistr: true */
var base64pdfData = '...'; //should contain base64 representing the PDF
function base64ToUint8Array(base64) {
var raw = atob(base64);
var uint8Array = new Uint8Array(new ArrayBuffer(raw.length));
for (var i = 0, len = raw.length; i < len; ++i) {
uint8Array[i] = raw.charCodeAt(i);
}
return uint8Array;
}
return base64ToUint8Array(base64pdfData);
}
Enable Text Selection in PDF.JS
Step 1: Adding a Element to Hold the Text Layer
<div id="text-layer"></div>
This div will be in addition to the element where the PDF is rendered, so the HTML will look like :
<canvas id="pdf-canvas"></canvas>
<div id="text-layer"></div>
Step 2 : Adding CSS for Text Layer
Add the following to your CSS file :
#text-layer {
position: absolute;
left: 0;
top: 0;
right: 0;
bottom: 0;
overflow: hidden;
opacity: 0.2;
line-height: 1.0;
}
#text-layer > div {
color: transparent;
position: absolute;
white-space: pre;
cursor: text;
transform-origin: 0% 0%;
}
Step 3: Getting the PDF Text
After the PDF has been rendered in the canvas, you need to get the text contents of the PDF, and place that text in the text layer.
// page is the page context of the PDF page
// viewport is the viewport required in renderContext
// For more see https://usefulangle.com/post/20/pdfjs-tutorial-1-preview-pdf-during-upload-wih-next-prev-buttons
page.render(renderContext).then(function() {
// Returns a promise, on resolving it will return text contents of the page
return page.getTextContent();
}).then(function(textContent) {
// PDF canvas
var pdf_canvas = $("#pdf-canvas");
// Canvas offset
var canvas_offset = pdf_canvas.offset();
// Canvas height
var canvas_height = pdf_canvas.get(0).height;
// Canvas width
var canvas_width = pdf_canvas.get(0).width;
// Assign CSS to the text-layer element
$("#text-layer").css({ left: canvas_offset.left + 'px', top: canvas_offset.top + 'px', height: canvas_height + 'px', width: canvas_width + 'px' });
// Pass the data to the method for rendering of text over the pdf canvas.
PDFJS.renderTextLayer({
textContent: textContent,
container: $("#text-layer").get(0),
viewport: viewport,
textDivs: []
});
});
source: https://usefulangle.com/post/90/javascript-pdfjs-enable-text-layer
setupAnnotations = (page, viewport, canvas, annotationLayerDiv) => {
let pdfjsLib = window['pdfjs-dist/build/pdf'];
let pdfjsViewer = window['pdfjs-dist/web/pdf_viewer'];
//BELOW--------- Create Link Service using pdf viewer
let pdfLinkService = new pdfjsViewer.PDFLinkService();
page.getAnnotations().then(function (annotationsData) {
viewport = viewport.clone({
dontFlip: true
});
let pdf_canvas = canvas;
// Render the annotation layer
annotationLayerDiv.style.left = pdf_canvas.offsetLeft + 'px';
annotationLayerDiv.style.top = pdf_canvas.offsetTop + 'px';
annotationLayerDiv.style.height = viewport.height + 'px';
annotationLayerDiv.style.width = viewport.width + 'px';
pdfjsLib.AnnotationLayer.render({
viewport: viewport,
div: annotationLayerDiv,
annotations: annotationsData,
page: page,
linkService: pdfLinkService,
enableScripting: true,
renderInteractiveForms: true
});
}
IMP ---- Do not forget to add this CSS
.annotation-layer{
position: absolute;
left: 0;
top: 0;
right: 0;
bottom: 0;
overflow: hidden;
opacity: 1;
}
.annotation-layer section{
position: absolute;
cursor: pointer;
}
.annotation-layer section a{
display: block;
width: 100%;
height: 10px;
}
In above example, Link service instance is created using class in pdf viewer, which is being passed as parameter to annotation layer render method.
Please refer source code of PDF.js refer to /web/pdf_viewer.js - class PDFLinkService for more information.
PDF.js version - v2.9.359