Dynamically creating image link Jquery or vanilla Javascript - javascript

I am trying to figure out how to dynamically create a image with caption below it. I would like it so that when a user clicks the image or caption it redirects to a different page. I have a feeling what I am doing is wrong on many levels.
function createFrame(data){
// <div><img src=""><div></div></img></div>
var div = document.createElement('div');
var a = document.createElement('a');
var img = document.createElement('img');
a = a.innerHTML(img);
div.innerHTML(a);
return div;
});

Using .append() in jquery, you can append the image tags in the desired div.
$("#btn").click(function(){
$("#imgDiv").append('<img src="" alt="Image"/>')
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="btn">Create Image Link</button>
<div id="imgDiv">
</div>

Following your idea of creat that you want, i did the following:
function createFrame(data){
// <div><img src=""><div></div></img></div>
var div = document.createElement('div');
var a = document.createElement('a');
a.href = 'your-href-link';
var img = document.createElement('img');
img.src = 'your-src-link';
var div_caption = document.createElement('div');
a.appenchild(img);
a.appenchild(div_caption);
div.appenchild(a);
});

There are several ways to do it with pure JS or with frameworks (jquery..).
Pure js :
Level 1 simple
function createFrame(src){
return "<div>"+
"<a href='"+src+"' target='_blank'>"+
"<img src='"+src+"' alt='demo'/>"+
"</a>"+
"</div>";
}
document.getElementById("demo").innerHTML = createFrame("http://lorempixel.com/100/100");
<div id="demo"></div>
<br/>
2nd Level
document.getElementById("demo").innerHTML = createFrame("http://lorempixel.com/100/100");
function createFrame(src=false, divID = false, link=false, aID=false, imgID=false, openToNewTab = false){
$html = "";
$html += "<div ";
if(divID !== false) $html += "id = '"+divID+"' ";
$html += ">";
$html += " <a href='";
$html += (link !== false)? link+"' ":"#' ";
$html += (openToNewTab !== false)? " target='_blank'":"";
$html += ">";
$html += "<img src='"+src+"' ";
$html += imgID? " id='"+imgID+"'":"";
$html += " /></a></div>";
return $html;
}
<div id="demo"></div>
3rd Level
var html = createFrame(
{"src":"http:lorempixel.com/100/100", "id":"img"},// img attributes
{"href":"http:lorempixel.com/100/100", "class":"caption", "target":"_blank"}, // a attributes
{"class":"imgContainer"}//div
);
document.getElementById("demo").innerHTML = html;
function createFrame(img={}, a={}, div={}){
var html = "";
html = TagGenerator("img", img, "",true);
html = TagGenerator("a", a, html);
html = TagGenerator("div", div, html);
return html;
}
function TagGenerator(tagname, attr=[], html="", endAbleTag=false){
var tag = "<"+tagname+" ", i;
for (i in attr)
tag += i+"='"+attr[i]+"' ";
if(!endAbleTag) tag += ">"+html+" </"+tagname+">";
else tag += "/>";
return tag;
}
<div id="demo"></div>

Related

onclick() event is not working in javascript and span tag

I have written the below code to display textarea in the form but it is not working in javaascript. the real requirement is when i click on reply in span tag a text area with a button should appear but it is not happening. Is it happening because the script part is below the span tag or something else is the reason for it just asking.
echo "<center>";
echo "<span class=c20 id=like1>Like</span>";
echo "<span class=c21 id=reply1 onclick='myFunction()'>Reply</span>";
echo "<span class=c22 id=display1>Display</span>";
echo "</center>";
echo "<br><br>";
echo "<span id=reply3></span>";
echo "<br><br>";
'$row01["Email"]'; '$row01["Name"]'; '$row01["Message"]'; '$row01["Picture"]'; '$row01["Status"]'; '$replybymail'; '$replybyname'; '$row01["Password"]';
<script type="text/javascript">
document.getElementById("reply1").addEventListener("click", myFunction);
function myFunction() {
reply();
}
function reply() {
var x = document.getElementById("reply3").value;
var email1 = document.getElementById("i1").value;
var pass1 = document.getElementById("i8").value;
var name1 = document.getElementById("i2").value;
var pict1 = document.getElementById("i4").value;
var status1 = document.getElementById("i5").value;
var message1 = document.getElementById("i3").value;
var replybymail1 = document.getElementById("i6").value;
var replybyname1 = document.getElementById("i7").value;
var email;
var picture;
var name;
var status;
var password;
var mess;
var replybymail;
var replybyname;
var url= 'profileto.php?email='+ email1+'&picture='+ pict1+'&name='+ name1+'&status=' + status1+'&password='+ pass1+'&mess=' + message1+'&replybymail='+ replybymail1 +'&replybyname='+ replybyname1+' ';
var forms = "<form id='replyform' method='POST' class='form1' onsubmit = 'myFunction2()'>
<center><textarea cols='40' rows='50' class = 'c61' name='reply' style= 'height: 27px'></textarea></center><br>
<center><input type='submit' value ='Reply' class='c60'></center></form><br><br>";
document.getElementById("reply3").innerHTML = forms;
document.getElementById("replyform").action = url;
if(x.style.display === "none" )
{
x.style.display = "block";
} else {
x.style.display = "none";
}
}
function myFunction2()
{
alert("Your post is published");
}
</script>
The problem is that you are getting the element to set OnClickListener
JS is not able to find the element!
You are not using inverted commas when set attribute value.
Change this line:
echo "<span class=c21 id=reply1 onclick='myFunction()'>Reply</span>";
To:
echo "<span class=\"c21\" id=\"reply1\" onclick='myFunction()'>Reply</span>";
\ is used to escape " OR '.
Always add \ before " OR '. Like this \".
Not like this "\.

Get element from HTML object javascript

I have a HTML String and I want to get img element and initialize it.
var discountItem = '<li class="sidebar-brand" style="font-weight: bold; color: #9999 class="col-item">' +
'<div class="post-img-content">' +
'<img src=" " class="img-responsive" id="mimo" />'+
'<span class="post-title">'+
'<b>Perfumes</b><br>'+
'<b>Clássico</b>'+
'</span>'+
'<span class="round-tag">-15%</span>'+
'</div>'+
'</li>';
var k = app.clone(discountItem);
var df = document.createDocumentFragment();
// create a placeholder node to hold the innerHTML
var el = document.createElement('body');
el.innerHTML = k;
// append to the document fragment
df.appendChild(el);
// execute .getElementById
console.log(df.getElementByClassName('img-responsive');
view += k;
clone : function(obj){
try{
var copy = JSON.parse(JSON.stringify(obj));
} catch(ex){
console.log("you are using an old navigator");
}
return copy;
}
I tried this but it doesn't work.
My goal is to initialize the src of the image.
Could someone help me ?
If you're trying to find the img element, you can do a lot less work: Just create a body, append that HTML to it, and use querySelector:
var discountItem = '<li class="sidebar-brand" style="font-weight: bold; color: #9999 class="col-item">' +
'<div class="post-img-content">' +
'<img src=" " class="img-responsive" id="mimo" />'+
'<span class="post-title">'+
'<b>Perfumes</b><br>'+
'<b>Clássico</b>'+
'</span>'+
'<span class="round-tag">-15%</span>'+
'</div>'+
'</li>';
var body = document.createElement("body");
body.innerHTML = discountItem;
var img = body.querySelector(".img-responsive");
img.src = "source path here";

jquery added html code not worked

I started new project and I use jquery to add content to article
when I create a slider with this code:
$(".inserttabtext1").click(function () {
var count = parseInt($(".firsttabtextcount").attr("name"), 10);
var name = parseInt($(this).attr("name"));
var id = "#" + name;
var idi,idt,content,idic,idtc;
content = "<div class='short-tabs'><ul>";
for (var i = 1; i <= count; i++)
{
idi = "#ftti" + i;
idic = $(idi).val();
if (i == 1)
{
content += "<li class='active'><a href='#'> " + i + idic + "</a></li>";
}
else
{
content += "<li><a href='#'> "+ i + idic +"</a></li>";
}
}
content += "</ul>";
for (var i = 1; i <= count; i++)
{
if (i==1)
{
content += "<div class='active'>";
}
else
{
content += "<div>";
}
idt = "#fttt" +i;
idtc = $(idt).val();
content += "<p class='text-go-center'>"+idtc+"</p></div>";
}
content += "</div>";
$(id).html(content);
});
and put them into html code my text slider not worked
but when I put manual html code in my page it work
I use these code for copy my html code
$(id).html(content);
$(id).append(content);
where is my wrong?
create a function and put your slider codes inside it, then call it in $(document).ready, and call it again after adding html
$(document).ready(function(){
Init();
});
function Init(){
//Call your slide function here
}
call Init after Adding Html
$(id).html(content);
$(id).append(content);
Init();

parse HTMLElmentObject with innerHTML in javascript

I am building a cat clicker game. Where I Have five cat and each one has click function which increase count on every click.
I have created a DOM from javascript function, I have create image from document.create method so that I can attached event to it. So my javascript code contains both pure HTML and HTMLElementObj. fiddle.
But innerHTML is not paring the element which is creating by the document.createElement
function fac(name) {
this.name = name;
this.count = 0;
}
var cats = ['cat1', 'cat2', 'cat3', 'cat4', 'cat5']
function $(name) {
return document.querySelector(name);
}
var html = "";
for (var i = 0; i < cats.length; i++) {
var cat = new fac(cats[i])
html += "<div>";
html += "<div>" + cat.name + "</div>";
var elem = document.createElement('img');
elem.src = 'https://c2.staticflickr.com/2/1126/625069434_db86b67df8_n.jpg';
html += elem;
html += "<div class='count " + i + "'></div>";
html += "</div>";
elem.addEventListener('click', function() {
$('.count' + i).innerText = ++cat.count;
}, false);
$('#getClicked').innerHTML = html
}
You are mixing strings and dom elements and that won't work. Just do everything as strings
html += "<div>";
html += "<div>" + cat.name + "</div>";
var elem = "<img src='https://c2.staticflickr.com/2/1126/625069434_db86b67df8_n.jpg'>";
html += elem;
html += "<div class='count " + i + "'></div>";
or as dom elements (a bit more learning needed to start with but better in the long run)

Changing the content of all <pre> tags using JavaScript

I want to know how I change all the pre tags inside a document...
I'm using this:
var preContent = document.getElementById('code').innerHTML;
but this only changes the content of 1 pre tag... the one with the ID 'code'.
If you can show me how i can change all the pre tags using JavaScript I appreciate
Here's all the code:
window.onload = function () {
var preContent = document.getElementById('code').innerHTML;
var codeLine = new Array();
var newContent = '<table width="100%" border="1" '
+ 'cellpadding="0" cellspacing="0" >';
codeLine = preContent.split('\n');
for (var i = 0; i < codeLine.length; i++) {
newContent = newContent + '<tr><td class="codeTab1" >'
+ i.toString() + '</td><td class="codeTab2">'
+ codeLine[i] + '</td></tr>';
}
newContent = newContent + '</table>';
document.getElementById('code').innerHTML = newContent;
}
PS: This is to make a look like a normal compiler with numbers before the line
PPS: Each pre tag will have a different content and I want the same script to change it (if possible).
You can use getElementsByTagName:
var preElements = document.getElementsByTagName('pre');
for(var i = 0; i < preElements.length; ++ i)
{
var element = preElements[i];
/* modify element.innerHTML here */
}
First problem in you code . No two elements in a document can have same id .
So you can change it easily with jquery . look at the code .
$('pre').html("what ever text you want to show ");
Or with javascript you can do like this :
var x = document.getElementsByTagName('pre');
for(var i = 0; i < x.length; ++ i)
{
x.innerHTML = "what ever text you want to show";
}

Categories