JQuery How to create element in created element - javascript

There is a code I'm working on - https://jsfiddle.net/md_bender/pj6a1akz/3/. I need to create new elements and append them to the existing element ul. With creating elements and appending everything is OK.
But I don't know how to create child element in the created element. I need to create
<img src="path"/>
In the div I have created earlier in script. It must be like that
<div class="img-w js-popup">
<img src="path"/>
</div>
Delete
But only I can do is create as next sibling to the div
<div class="img-w js-popup"></div>
<img src="path"/>
Delete
Who can help me and solve my problem?

You can append img to div before you append that div to li. You can also write the same code like this Fiddle
$('<li/>')
.append($('<div/>', {
'class': 'img-w js-popup',
}).append($('<img/>', {
'src': '//www.gravatar.com/avatar/9142888a2ae6160f2faec90134eeafa3/?default=&s=80'
})))
.append($('<a/>', {
href: 'delete.php',
text: 'Delete'
}))
.appendTo('ul');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li>
<div>
<img src="//www.gravatar.com/avatar/9142888a2ae6160f2faec90134eeafa3/?default=&s=80" alt="" />
</div>
Delete
</li>
</ul>

The issue is because your append() call is on the li itself, not the div you just added. Try this:
var $div = $('<div/>', {
'class': 'img-w js-popup'
});
$('<img/>', {
'src': '//www.gravatar.com/avatar/9142888a2ae6160f2faec90134eeafa3/?default=&s=80'
}).appendTo($div)
$('<li/>').append($div).append($('<a/>', {
href: 'delete.php',
text: 'Delete'
})).appendTo('ul');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<ul>
<li>
<div>
<img src="//www.gravatar.com/avatar/9142888a2ae6160f2faec90134eeafa3/?default=&s=80" alt="" />
</div>
Delete
</li>
</ul>
With that said, you're using the most verbose method of creating HTML. As you're hard-coding all attributes, it can be simplified by just providing the plain string - or even by just cloning the previous li and appending that.

If do not need single DOMs (li, div, img) its easier to create static string and append whole into list, just like that (remember about backslashes):
$('ul').append("<li><div><img src=\"//www.gravatar.com/avatar/9142888a2ae6160f2faec90134eeafa3/?default=&s=80\" alt=\"\"/></div>Delete</li>");

$('<li/>')
.append($('<div/>', {
'class': 'img-w js-popup',
}))
.append($('<div/>', {
'id': 'idOFDiv'
}))
.append($('<a/>', {
href: 'delete.php',
text: 'Delete'
}))
.appendTo('ul');
$("#idOFDiv").append($('<img/>', {
'src': '//www.gravatar.com/avatar/9142888a2ae6160f2faec90134eeafa3/?default=&s=80'
}));

Related

How to get all the "a" elements inside this div?

A website on Chrome has the following structure:
<div class="divClass">
<a class="aClass"></a>
<a class="aClass"></a>
<a class="aClass"></a>
</div>
I'm using JQuery to get all the "a" elements inside the div. They all have the same class. The code I'm using in the devTools is this:
$("div[class='divClass'] > a")
But it only returns the first "a" element. How can I get all of them?
Snippet:
console.log($("div[class='divClass'] > a"))
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="divClass">
<a class="aClass"></a>
<a class="aClass"></a>
<a class="aClass"></a>
</div>
You can just use $('.divClass > a')
An alternative is to use find() which gets the descendants of each element in the current set of matched elements so it can be helpful here
$(".divClass").find("a")
More about find - https://api.jquery.com/find/
use .children method,
/*
var a1 = $(".divClass").children("a")[0].text;
var a2 = $(".divClass").children("a")[1].text;
var a3 = $(".divClass").children("a")[2].text;
*/
var aaa = $(".divClass").children("a").text();
console.log(aaa);
You can use a different selector, for instance:
$(".divClass > a.aClass")
This will find all a tags with class aClass that are immediate children of an element with class divClass. If you want to find all children throughout the DOM tree (i.e. grandchildren, great grandchildren, etc) then you can use omit the > operator.
You can then act on all elements matching these criteria (for instance .addClass("found"), or cycle through them individually using .each( function() { ....}) if you need to pull element specific information from them.
The demo below is fully commented.
DEMO
// Add click event to test button
$("#test").click( function() {
// ACT ON ALL IN ONE LINE
// Use jquery to find all direct children of elements with class divClass that are 'a' tags with class 'aClass'
// Add red border using CSS styles
$(".divClass > a.aClass").addClass("directChildren");
// Find grandchildren, great grandchildren, etc
// Turn color of text blue using CSS
$(".divClass a.aClass").addClass("allChildren");
// HOW TO CYCLE TRHOUGH EACH LINK
// Cycle through each, find them using same technique as above
$(".divClass > a.aClass").each( function() {
// Prove we've found each individual link
console.log($(this).text());
});
});
.directChildren {
border: red 2px solid;
}
.allChildren {
color: blue;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="divClass">
<a class="aClass">Link 1</a>
<a class="aClass">Link 2</a>
<a class="aClass">Link 3</a>
<div style="padding:12px;">
<a class="aClass">Grandchild Link 1</a>
</div>
</div>
<button id="test">Find Children</button>

How do you append an element by an ID obtained with this.id to another element?

I have several pictures in the same class, and when the class is clicked I get the ID of the picture using this.id. I want to take that ID and use it to move the picture that has been clicked. I am trying to append it to the span with the ID "yours."
$(".characters img").on("click",function(){
console.log(this.id);
$(this.id).prependTo("#yours");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class= "characters">
<img src="assets/images/luke.jpg" id="luke">
<img src="assets/images/rey.jpg" id="rey">
<img src="assets/images/kylo.jpg" id="kylo">
<img src="assets/images/snoke.jpg"id="snoke">
</div>
<div class = "text">
<h1> Your Character </h1>
<span id="yours"> </span>
<h1>Enemies Available to Attack</h1>
<span id="enemies"></span>
<h1> Defender</h1>
<span id="defender"></span>
</div>
Instantiate a new jQuery object with the image (this), and not this.id:
Change:
$(this.id).prependTo("#yours");
To:
$(this).prependTo("#yours");
While clicking on an img, target #yours element, empty it ( if desired ), then clone the clicked img and pass it to the html method since it accepts a jQuery object.
$(".characters img").on("click",function(){
// Empty "yours" and add the cloned clicked image
$("#yours").empty().html($(this).clone());
});

ColorBox - How to display div using class

My HTML structure is as follows:
<div class="parent">
<span class="read_more">Read More</span>
<div class="hidden description" id="description1">Description</div>
</div>
..
<div class="parent">
<span class="read_more">Read More</span>
<div class="hidden description" id="description2">Description</div>
</div>
My Js code which works for id if I give the id to each description div's
$(".read_more").on("click", function (e) {
var href = '#'+$(this).next().attr('id');
$(this).colorbox({ inline: true, href: href });
});
I am using ColorBox plugin.
When I click on Read More I need the Description to pop up. I am able to achieve this using id and I don't want to give id's to the description as this is dynamically generated. How could I achieve this using class? Is this possible?
Any help appreciated!
ColorBox also accepts HTML. Try the below
$(".read_more").on("click", function (e) {
var html = '#'+$(this).next().html();
$(this).colorbox({ inline: true, html: html });
});
If your css class 'hidden' applies display:none; try this
css:
.not_hidden { display:block }
jquery
$('.read_more').click(function(){
$(this).next('.description').addClass('not_hidden')
})
edited to use classes.
Solved!
I am sorry. I should have paid more attention to the documentation.
// Using a jQuery object:
$(".read_more").on("click", function (e) {
e.preventDefault();
var $desc = $(this).next();
$(this).colorbox({ inline: true, href: $desc });
});

Launch fancyBox from button click

Im stuck with a little problem with fancyBox v2.
I want to launch fancyBox on button click. Once clicked, it will load all the images from the list (from the src attribute of the ).
I have created this jsfiddle to show what I am trying to do: http://jsfiddle.net/fPFZg/
jQuery(document).ready(function($) {
$('button').on('click', function() {
$.fancybox();
});
});
Can anybody see how this would be possible?
I had the same question and found the following to be a simpler method:
HTML
<button class="fancybox" value="Open Fancybox">Open Fancybox</button>
<div class="hidden" id="fancybox-popup-form">
(your Fancybox content goes in here)
</div>
jQuery
$('.fancybox').click(function () {
$.fancybox([
{ href : '#fancybox-popup-form' }
]);
});
CSS
.hidden { display: none; }
Further Reading
Fancybox Docs (click the "API Methods" tab, then read up on the first method, which is called "Open").
you can use it like this:
$.fancybox.open([
{
href : 'http://fancyapps.com/fancybox/demo/1_b.jpg',
title : '1st title'
},
{
href : 'http://fancyapps.com/fancybox/demo/2_b.jpg',
title : '2nd title'
}
], {
padding : 0
});
Your code doesn't work because this $.fancybox(); doesn't tell fancybox what to open so does nothing.
What I would do, if you don't want to edit every link in your html, is:
1). add an ID to the <ul> tag so we can use that selector like
<ul id="images">
2). bind fancybox to all <a> anchors that are child of your element #images like
var fancyGallery = $("#images").find("a"); // we cache the selector here
fancyGallery.attr("rel","gallery").fancybox({
type: "image"
});
notice that we are adding a rel attribute on the fly to all anchors so they will be part of the same gallery
3). bind a click event to the button (I would recommend you to give it an ID too so it won't mess with other possible buttons in the future) that triggers the existing fancybox script as above, so with this html
<button id="fancyLaunch">Launch Fancybox</button>
use this script
$('#fancyLaunch').on('click', function() {
fancyGallery.eq(0).click(); // triggers a click
});
notice that we used the method .eq() to launch the gallery from the first item (first index in javascript is always 0)
Summarizing, your whole script may look like this :
jQuery(document).ready(function($) {
var fancyGallery = $("#images").find("a");
fancyGallery.attr("rel","gallery").fancybox({
type: "image"
});
$('#fancyLaunch').on('click', function() {
fancyGallery.eq(0).click();
});
});
See JSFIDDLE
Your html:
<ul>
<li>
<a href="http://placekitten.com/400/400" title="" class="fancybox">
<img src="http://placekitten.com/100/100" alt="" />
</a>
</li>
<li>
<a href="http://placekitten.com/400/400" title="" class="fancybox">
<img src="http://placekitten.com/100/100" alt="" />
</a>
</li>
<li>
<a href="http://placekitten.com/400/400" title="" class="fancybox">
<img src="http://placekitten.com/100/100" alt="" />
</a>
</li>
<li>
<a href="http://placekitten.com/400/400" title="" class="fancybox">
<img src="http://placekitten.com/100/100" alt="" />
</a>
</li>
Your jQuery:
$(document).ready(function() {
$('button').on('click', function() {
$.fancybox($("a.fancybox"));
});});

How to have multiple data-bind attributes on one element?

I need to have multiple data bindings on one element. For example, I want a href as well as a html data-binding on one a tag. I have tried this,
<a data-bind="html: name"
data-bind="attr: { href: url }"
data-bind="attr: { 'data-prop': xyz }">
</a>
But this doesn't work. It seems knockout only supports binding one data-bind property? How to bind both the href, the inner html, and a custom "data-prop" attribute on one element?
Like this:
<a data-bind="html: name, attr: { href: url }">
You use comma-separated bindings - the attribute is the same as passing an object:
{
html: name,
attr: { href: url }
}
Or, if you're asking about multiple attr bindings at once:
<a data-bind="html: name, attr: { href: url, 'data-prop': FullName }">
This is how I implemented the source attribute and click event using data-bind. You may find it useful.
<img data-bind="{click: function(data, event) {ESVendorWidget.loadFunction(data,event)},
attr: {src: $data.Photo.PhotoUrl }}"
alt="package pic" class="big" />
I simply use:
<input type="checkbox"
data-bind="click: callFunction(), checkedValue: 0, checked: Card.Days">
for a checkbox element.
you can use multiple properties using , like below
<a data-bind="attr: { href: url, id: id , class: classvalue}">
object like this
{ url: 'http://stackoverflow.com', id:'newid' , classvalue: 'classname' }
you can use like below
data-bind="text: method.method_title, attr: {'id': 'label_method_' +
method.method_code}"

Categories