create a div with a text where i click an image - javascript

I have an image in HTML and i want the user to write an input in HTML and then if he click on the image it will create a colored div which is written inside the input, the position of this div is based of the coordinates where the user clicked (not centered, a little on top and to the left), for now I can create the rectangular div, but i don't know how to put a text in it.
let listaAre = [];
let quantiClic = 0;
document.getElementById('blah').addEventListener('click', event => {
document.getElementById('squareContaine').innerHTML =
document.getElementById('squareContaine').innerHTML +
'<div id="squar' + quantiClic + '" style="background-color: blue; height: 50px; width: 50px; position: absolute;"></div>';
document.getElementById('squar' + quantiClic).style.top = (event.pageY - Number(document.getElementById('dimensione').value) / 2) + 'px';
document.getElementById('squar' + quantiClic).style.left = (event.pageX - Number(document.getElementById('dimensione').value) / 2) + 'px';
document.getElementById('squar' + quantiClic).style.width = Number(document.getElementById('dimensione').value)/4 + 'px';
document.getElementById('squar' + quantiClic).style.height = Number(document.getElementById('dimensione').value)/10 + 'px';
document.getElementById('squar' + quantiClic).style.background =(document.getElementById('colorebordo').value);
listaAre.push({
x: (event.offsetX - Number(document.getElementById('dimensione').value) / 2),
y: (event.offsetY - Number(document.getElementById('dimensione').value) / 2),
width: Number(document.getElementById('dimensione').value),
height: Number(document.getElementById('dimensione').value),
background:(document.getElementById('colorebordo').value)
});
document.getElementById('squar' + quantiClic).addEventListener('click', function (e) {
this.style.display = 'none';
});
quantiClic = quantiClic + 1;
});
article, aside, figure, footer, header,
hgroup, menu, nav, section { display: block; }
.fasciaalta {
position: fixed;
background-color: white;
}
<div class="fasciaalta">
<input type="color" id="colorebordo">
<input type="text" id="nome">
<input type="number" id="dimensione" value="200">
<hr size="2px" color="blue" width="100">
</div>
<img id="blah" src="montagna.jpg" alt="your image" />
<div id="squareContaine"></div>
<div id="previewImage"></div>

You can get the coordinates of the mouse on the event click by accessing the clientX and clientY properties of the event object. Then you simply tell the new element to use them as top and left styles to position it.
Snippet
document.getElementById('blah').addEventListener('click', function(event) {
var div = document.createElement("DIV"); // Create a <div> element
var t = document.createTextNode("HELLO");// Create a text node
div.appendChild(t); // Append the text to <div>
document.body.appendChild(div); //Add <div> to document
div.style.position = 'absolute'; //Make its position absolute
//Set the coordinates
div.style.left = event.clientX + "px";
div.style.top = event.clientY + "px";
})
<div>
<img id="blah" src="http://img1.wikia.nocookie.net/__cb6/nyancat/images/5/50/Wiki-background" alt="your image" />
</div>
Extra
If instead of creating a new div, you want to use one simply access that element with getElementById and change its properties instead. I've made the example as simple as possible so that it can apply to not only your case but anyone else's trying to solve their issue.

If you need the text value then all you need is to change the first 2 statements of your click function. - Check this Codepen
1) Onclick, get the value of the textbox like so
var val = document.getElementById('nome').value;
2) Next insert this val into your innerHTML statement
document.getElementById('squareContaine').innerHTML =
document.getElementById('squareContaine').innerHTML +
'<div id="squar' + quantiClic + '" style="background-color: blue; height: 50px; width: 50px; position: absolute;">'+ val + '</div>';
Scroll the very end of the above statement to see the val inserted.
Also do not forget to change the color of the text if the background of the box is black.
document.getElementById('blah').addEventListener('click', event => {
var val = document.getElementById('nome').value; //added
//below statement changed
document.getElementById('squareContaine').innerHTML =
document.getElementById('squareContaine').innerHTML +
'<div id="squar' + quantiClic + '" style="background-color: blue; height: 50px; width: 50px; position: absolute;">'+ val + '</div>';
.. rest of the code remain the same ..
});

Related

Set specific image to Div

I set multiple image sources for a div using javascript function. I want that when user clicks to the button then only a specific image set to that div.
function changeColor1() {
document.getElementById("myDIV").style = "background-image:url(coloredshirtsimages/coloredwithoutsleeve/red_withoutsleeve.png)"
document.getElementById("myDIV").style = "background-image:url(coloredshirtsimages/coloredhalfsleeveroundneck/red_halfsleeve.png)"
document.getElementById("myDIV").style = "background-image:url(coloredshirtsimages/coloredfullhalf/red_fullhalfsleeve.png)"
document.getElementById("myDIV").style = "background-image:url(coloredshirtsimages/coloredfullsleeve/red_fullsleeve.png)"
document.getElementById("myDIV").style = "background-image:url(coloredshirtsimages/coloredfullsleevev-neck/red_fullsleevevneck.png)"
document.getElementById("myDIV").style = "background-image:url(coloredshirtsimages/coloredshirtsimages/coloredvneck/red_vneck.png)"
}
<div id="myDIV"></div>
<button style="background-color:red;outline:none" class="colors" onclick="changeColor1()"></button>
#myDIV {
width: 550px;
height: 650px;
background-image: url(coloredshirtsimages/coloredhalfsleeveroundneck/white_halfsleeve.png);
border: 2px solid black;
color: orange;
float: right;
margin-top: 200px;
background-repeat: no-repeat;
}
I changed the image using css and javascript now the image belongs to particular category for example(white_vneck)is goes to div but problem is that only one image was gone to div. I want that other image (red_vneck.png) goes to div when i clicked the button in place of white_vneck.
Please feel free to ask a question if you have any confusion
Pass a parameter to your function to help it understand which image you wish to display:
onclick="changeColor1('abc.png')"
function changeColor1(pic) {
document.getElementById("myDIV").style = "background-image:url(" + pic + ")";
}
According your code snippet:
function changeColor1(pngName) {
document.getElementById("myDIV").style = "background-image:url("+pngName+")";
}
<div id="myDIV"></div>
<button style="background-color:red;outline:none" class="colors" onclick="changeColor1('coloredshirtsimages/coloredwithoutsleeve/red_withoutsleeve.png')"></button>
For selecting random image:
onclick="changeColor1()"
var pics =[
'coloredwithoutsleeve/red_withoutsleeve.png' ,
'coloredhalfsleeveroundneck/red_halfsleeve.png',
'coloredfullhalf/red_fullhalfsleeve.png',
'coloredfullsleeve/red_fullsleeve.png',
'coloredfullsleevev-neck/red_fullsleevevneck.png',
'coloredshirtsimages/coloredvneck/red_vneck.png'
];
function changeColor1() {
//random selection of pic
var picIndex = Math.floor(Math.random() * pics.length);
document.getElementById("myDIV").style = "background-image:url(coloredshirtsimages/" + pics[picIndex] + ")";
}

Converting javascript generated frames to divs

I have some old code that I am trying to convert to divs. It contains frames that have no target src, just JavaScript to generate a page.
Below is the code...
var editboxHTML =
'<html class="expand close">' +
'<head>' +
'<style type="text/css">' +
'.expand { width: 100%; height: 100%; }' +
'.close { border: none; margin: 0px; padding: 0px; }' +
'html,body { overflow: hidden; }' +
'<\/style>' +
'<\/head>' +
'<body class="expand close" onload="document.f.ta.focus(); document.f.ta.select();">' +
'<form class="expand close" name="f">' +
'<textarea class="expand close" name="ta" wrap="hard" spellcheck="false">' +
'<\/textarea>' +
'<\/form>' +
'<\/body>' +
'<\/html>';
var defaultStuff = 'This top frame is where you put your code.';
var extraStuff = '';
var old = '';
function init() {
window.editbox.document.write(editboxHTML);
window.editbox.document.close();
window.editbox.document.f.ta.value = defaultStuff;
update();
}
function update() {
var textarea = window.editbox.document.f.ta;
var d = dynamicframe.document;
if (old != textarea.value) {
old = textarea.value;
d.open();
d.write(old);
if (old.replace(/[\r\n]/g, '') == defaultStuff.replace(/[\r\n]/g, ''))
d.write(extraStuff);
d.close();
}
window.setTimeout(update, 150);
}
<frameset onload="init();" rows="50%,50%" resizable="no">
<frame name="editbox" src="javascript:'';">
<frame name="dynamicframe" src="javascript:'';">
</frameset>
This code has a user input box at the top to input HTML code into, and the bottom displays what that code would look like in a browser.
How would I manipulate this code to work with divs instead of frames, so I can include extra styling, and so that it is not fully depreciated in HTML5.
If your answer includes AJAX, please can you explain it as I am not familiar with that coding.
EDIT: If there is no div alternative, is there an iframe alternative?
Answer Updated
CSS Fixed
Error fixed
Jquery way:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script>
var editboxHTML =
'<html class="expand close">' +
'<head>' +
'<style type="text/css">' +
'.expand { width: 100%; height: 50%; }' +
'.close { border: none; margin: 0px; padding: 0px; }' +
'html,body { overflow: hidden; }' +
'<\/style>' +
'<\/head>' +
'<body class="expand close">' +
'<form class="expand close" name="f">' +
'<textarea class="expand close" name="ta" wrap="hard" spellcheck="false">qweqwe' +
'<\/textarea>' +
'<\/form>' +
'<\/body>' +
'<\/html>';
var defaultStuff = 'This top frame is where you put your code.';
var extraStuff = '';
var old = '';
function init() {
$("#editbox").html(editboxHTML);
$("#editbox form[name='f'] [name='ta']").focus();
$("#editbox form[name='f'] [name='ta']").val(defaultStuff);
update();
}
function update() {
var textarea = $("#editbox form[name='f'] [name='ta']");
var d = $("#dynamicframe");
if (old != textarea.val()) {
old = textarea.val();
if (old != undefined){
d.html(old);
if (old.replace(/[\r\n]/g, '') == defaultStuff.replace(/[\r\n]/g, '')){
d.append(extraStuff);
}
}
else{
d.html("old undefined");
}
}
setTimeout("update()", 150);
}
</script>
<button onclick="init()">EDIT</button>
<div id="editbox"></div>
<div id="dynamicframe"></div>
you can just create one div tag with id say <div id='editbox' /> and add one line code in your update function document.getElementById("editbox").innerHTML=editboxHTML;

Box shadow won't "none" in JavaScript

My goal is to have a div that shows content and have a box shadow once clicked. Then I want to click on the div again to hide the content and box shadow. All is working great except for the box shadow that won't be hidden once its been clicked on in my second function that sets it to none. Why will this not work?
The HTML:
<div class="col-md-4 top" id="time">
<div class="clickme" id="clickme" onclick="clickme();
return false;">
<p>Click here for the time and date!</p>
</div>
</div>
The JavaScript:
function clickme(){
document.getElementById("clickme").style.display = 'none';
document.getElementById("time").style.boxShadow = "inset 6em 6em 6em #3B3130";
document.getElementById('time').innerHTML = "<h2 onclick='revert();''>It is " + theTime + " and the date is " + theDate + "</h2>";
}
function revert(){
document.getElementById('time').innerHTML = "";
document.getElementById("clickme").style.display = 'inline';
document.getElementById("time").style.boxShadow = 'none';
}
It's because you "destroy" the div #clickme when you modify the inner HTML of its parent.
See it working just fine when I moved the elements a bit:
function clickme() {
var theTime = 'some time';
var theDate = 'some date';
document.getElementById("clickme").style.display = 'none';
document.getElementById("time").style.boxShadow = "inset 6em 6em 6em #3B3130";
document.getElementById('time').innerHTML = "<h2 onclick='revert();''>It is " + theTime + " and the date is " + theDate + "</h2>";
}
function revert() {
document.getElementById('time').innerHTML = "";
document.getElementById("clickme").style.display = 'inline';
document.getElementById("time").style.boxShadow = 'none';
}
<div class="col-md-4 top" id="time"></div>
<div class="clickme" id="clickme" onclick="clickme();
return false;">
<p>Click here for the time and date!</p>
</div>
And don't forget - stuff like that is usually done using classes, not by applying styles directly.
#Shoms already identified the error in your code but I just want to give you a little more direction. I find it useful to move logic into the CSS wherever possible and just use javascript to add and remove classes. The advantage here is that you can easily fiddle with the CSS to change the look in different states without changing the javascript. Here is a possible solution.
var box = document.getElementById("box");
box.onclick = function() {
if (box.className.indexOf("clicked") == -1) {
box.className = "clicked";
} else {
box.className = "";
}
}
#box #time {
display: none;
}
#box.clicked {
box-shadow: 1em black;
}
#box.clicked #firstMessage {
display: none;
}
#box.clicked #time {
display: block;
}
<div id="box">
<p id="firstMessage">Click here for the time and date!</p>
<p id="time">Time to get a watch!</p>
</div>
Try this
document.getElementById("time").style.boxShadow = null;

Slick slider margin issues lazyYT

I am using lazyYT to load youtube video's faster. The loaded lazyYT videos are then placed in the slick slider. What then happens is that the video's are sticking together instead of a nice margin between every video. So I manually added a class to the video div
<div class="js-lazyYT" id="video-slide" data-youtube-id="<?php echo $video['video_link']; ?>" data-width="500" data-height="425"></div>
and gave it a margin which is working fine until the first video comes loaded back again. They paste together until all three first video's are visible again.
#video-slide{
width: 500px !important;
height: 425px !important;
margin-right: 10px;
-webkit-border-radius: 15px;
-moz-border-radius: 15px;
border-radius: 15px;
}
It looks like the first 3 entries in the slider reload the slider again when they are visible. Any idea?
;(function ($) {
'use strict';
function setUp($el) {
var width = $el.data('width'),
height = $el.data('height'),
ratio = $el.data('ratio'),
id = $el.data('youtube-id'),
aspectRatio = ['16', '9'],
paddingTop = 0,
youtubeParameters = $el.data('parameters') || '';
if (typeof width === 'undefined' || typeof height === 'undefined') {
height = 0;
width = '100%';
aspectRatio = (ratio.split(":")[1] / ratio.split(":")[0]) * 100;
paddingTop = aspectRatio + '%';
}
$el.css({
'position': 'relative',
'height': height,
'width': width,
'padding-top': paddingTop,
'background': 'url(http://img.youtube.com/vi/' + id + '/hqdefault.jpg) center center no-repeat',
'cursor': 'pointer',
'background-size': 'cover'
})
.html('<p id="lazyYT-title-' + id + '" class="lazyYT-title"></p><div class="lazyYT-button"></div>')
.addClass('lazyYT-image-loaded');
$.getJSON('https://gdata.youtube.com/feeds/api/videos/' + id + '?v=2&alt=json', function (data) {
$('#lazyYT-title-' + id).text(data.entry.title.$t);
});
$el.on('click', function (e) {
e.preventDefault();
if (!$el.hasClass('lazyYT-video-loaded') && $el.hasClass('lazyYT-image-loaded')) {
$el.html('<iframe width="' + width + '" height="' + height + '" src="//www.youtube.com/embed/' + id + '?autoplay=1&' + youtubeParameters + '" style="position:absolute; top:0; left:0; width:100%; height:100%;" frameborder="0" allowfullscreen></iframe>')
.removeClass('lazyYT-image-loaded')
.addClass('lazyYT-video-loaded');
}
});
}
$.fn.lazyYT = function () {
return this.each(function () {
var $el = $(this).css('cursor', 'pointer');
setUp($el);
});
};
}(jQuery));
I was looking at the lazyYT site and found their example:
<div class="container">
<div class="js-lazyYT" data-youtube-id="_oEA18Y8gM0" data-width="560" data-height="315" data-parameters="rel=0"></div>
</div>
Given that, you might try:
.myclass {
margin-left: 5px;
}
<div class="container">
<div class="js-lazyYT myclass" data-youtube-id="_oEA18Y8gM0" data-width="560" data-height="315" data-parameters="rel=0"></div>
</div>
or
<div class="container">
<div class="js-lazyYT" data-youtube-id="_oEA18Y8gM0" data-width="560" data-height="315" data-parameters="rel=0"> style='margin-left: 5px'</div>
</div>
or
.myclass div {
margin-left: 5px;
}
<div class="container myclass">
<div class="js-lazyYT" data-youtube-id="_oEA18Y8gM0" data-width="560" data-height="315" data-parameters="rel=0"></div>
</div>

why manual scrolling stop when i added auto scrolling in my page query

I am facing one problem .Actually I am working with socket programming in which I am getting data from server after a reqular interval of time.In beginning I am able to scroll my div when data is coming from server .But I add auto scroll code it start auto scrolling and stop manual scrolling.I will explain more i detail When data come from server I save that data in html or text file .When i click button for review it only show data upto the height of div..so i can solve problem with me,,
Here is css..!!
div.left, div.right {
float: left;
padding: 10px;
}
#realTimeContents {
overflow - y: scroll;
}
Hers is my html
<div data-role="fieldcontain" class="sliderContend_h" style="display: none; padding-top:10px;">
<input type="range" name="slider-2" id="slider-2" value="15" min="15" max="25" class="slider_h" data-highlight="true" />
</div>
<img src="img/ajax_loader_blue_512.gif" id="loadingImg" style='vertical-align: middle ;margin-left: 150px; margin-top: 200px; visibility:visible;'>
<div data-role="content" data-theme="d">
<div class="container">
<div id="realTimeContents" class="left realtimeContend_h" style="width:100%;height:1100px;"></div>
<!--div id="realTimeContents" class=" right realtimeContend_h">
</div-->
<div class="cursor" style="font-size:23px;">|</div>
</div>
</div>
Here is my js..
function nativePluginResultHandler(result) {
var isappend = window.localStorage.getItem("isAppendButtonClick");
if (isappend == 'true') {
$('#loadingImg').hide();
var currentTime = new Date()
var hours = currentTime.getHours()
var minutes = currentTime.getMinutes()
if (minutes < 10) {
minutes = "0" + minutes
}
var lines = result.split('<br/>');
$.each(lines, function () {
var text = "<span style='margin-left: 50px;'>" + this + "</span>";
$('#realTimeContents').append("<b>" + hours + ":" + minutes + " " + "</b> " + text + "<br/>");
});
var elem = document.getElementById('realTimeContents');
elem.scrollTop = elem.scrollHeight;
// $('#realTimeContents').prepend('<p>'+result+'</p>');
console.log(result + "************naveen***************");
// $('#realTimeContents' ).append('<p>'+result+'</p>');
}
}
How to start scrolling (manually when user scroll that actually div is not responded.It stand straight without any change state

Categories

Resources