Creating div code using Javascript - javascript

While using masonary example, we can create this code to generate new masonary divs.
function getItemElement() {
var elem = document.createElement('div');
var wRand = Math.random();
var hRand = Math.random();
var widthClass = wRand > 0.92 ? 'w4' : wRand > 0.8 ? 'w3' : wRand > 0.6 ? 'w2' : '';
var heightClass = hRand > 0.85 ? 'h4' : hRand > 0.6 ? 'h3' : hRand > 0.35 ? 'h2' : '';
elem.className = 'item ' + widthClass + ' ' + heightClass;
return elem;
}
$( function() {
var $container = $('.masonry').masonry({
columnWidth: 60
});
$('#append-button').on( 'click', function() {
var elems = [ getItemElement(), getItemElement(), getItemElement() ];
$container.append( elems ).masonry( 'appended', elems );
});
});
This code generates this div with random heights and widths
<div class="item"></div>
I want to generate this code, using javascript, please help me in this, i'm very weak in JS:
<div class="product desat">
<div class="saleTag">
<div class="saleText">Sale</div>
<div class="trunImg"><img src="img/saleTagTrunImg.png" alt=""></div>
</div>
<div class="entry-media">
<img src="images/jewelry/280128_238089139552597_218540758174102_904483_8113368_o.jpg" alt="" class="lazyLoad thumb desat-ie" />
<div class="hover">
<ul class="icons unstyled">
<li>
<a href="images/women/skirt/430041-0014_1.jpg" class="circle" data-toggle="lightbox">
<span>View Detail</span>
</a>
</li>
</ul>
</div>
</div>
<div class="entry-main arrow_box">
<h5 class="entry-title">
Neckless
</h5>
<div class="entry-price">
<s class="entry-discount">$ 35.00</s>
<strong class="accent-color price">$ 25.00</strong>
</div>
<div class="clearfix"></div>
</div>
</div>

I recommend using JQuery Templates..
https://github.com/BorisMoore/jquery-tmpl
very nice plugin that will give you functionality you need the way you are using with Arrays of Inputs..
Other than that, you're right there - adding dynamically these div using .append or .after;
I suggest you try this, then expand on it when you have it working basically..
$('#yourContainerDiv').append('<div>Div Inside Selected Div</div>');
or
$('#yourDivs:last').after('<div>New Div</div>')
Thanks,
JFIT

Related

Why is Bootstrap 4 carousel pause function not working when it's getting called from the event of an element inside of the carousel?

So I was trying to wrap my head around this issue, and I asked the question yesterday:
Carousel('pause') isn't working on mobile devices
I found the symptom so I'm asking a new question with a new focus.
The question title is not telling everything, because it would be too large:
This is only happening on phones, using mobile browsers, On desktop is totally fine.
Basically, if you have a Bootstrap 4 carousel, and you have any element that is inside of the div with the id of the carousel and you want to attach an event on that element (like a click) to pause the carousel, it wont work AT ALL, the slider keeps cycling.
I've tried click, mousedown, mouseup, I've tried setting the selector's click event on body, tried calling a click event on a selector that is outside to pause it, used parents, etc, and it wouldn't work.
Created a button that is right outside the carousel, attached a click event to it and it works.
I'm using the latest BS (4.4.1)
This is my code:
Blade file:
<div id='slider'>
<button class='pause-carousel' role='button'>Pause from outside</button>
<div id='sme-directory-gallery' class='carousel slide' data-ride='carousel'>
<button class='pause-carousel-2' role='button'>Pause from inside</button>
<div class='carousel-inner'>
#foreach($directoryInfo->videos as $index => $video)
<div class='item carousel-item {{ $index === 0 ? 'active' : '' }}' data-slide-number='{{ $index }}'>
<div class='video-mask'></div>
<div class='d-flex justify-content-center'>
<div class='embed-responsive embed-responsive-21by9'>
<iframe class='embed-responsive-item player' src='{{ 'https://www.youtube.com/embed/' . substr($video->url, strrpos($video->url, 'v=') + 2) }}' allowfullscreen></iframe>
</div>
</div>
</div>
#endforeach
#foreach($directoryInfo->images as $index => $image)
<div class='item carousel-item {{ ($index + sizeof($directoryInfo->videos)) === 0 ? 'active' : '' }}' data-slide-number='{{ $index + sizeof($directoryInfo->videos) }}'>
<div class='d-flex justify-content-center'>
<img src='{{ asset('storage/' . $image->path) }}' class='img-fluid' alt='imagen'>
</div>
</div>
#endforeach
<a class='carousel-control-prev' href='#sme-directory-gallery' role='button' data-slide='prev'>
<div class='rounded-circle'>
<span class='carousel-control-prev-icon' aria-hidden='true'></span>
<span class='sr-only'>Previous</span>
</div>
</a>
<a class='carousel-control-next' href='#sme-directory-gallery' role='button' data-slide='next'>
<div class='rounded-circle'>
<span class='carousel-control-next-icon' aria-hidden='true'></span>
<span class='sr-only'>Next</span>
</div>
</a>
</div>
<ul class='carousel-indicators list-inline'>
#foreach($directoryInfo->videos as $index => $video)
<li class='list-inline-item my-2 {{ $index === 0 ? 'active' : '' }}'>
<a id='carousel-selector-{{ $index + sizeof($directoryInfo->videos) }}' class='sme-gallery-anchor' data-slide-to='{{ $index }}' data-target='#sme-directory-gallery'>
<img src='{{ 'https://img.youtube.com/vi/' . substr($video->url, strrpos($video->url, 'v=') + 2) . '/mqdefault.jpg' }}' class='img-fluid'>
<div class='text-white sme-gallery-middle-icon'>
<span class='fas fa-play'></span>
</div>
</a>
</li>
#endforeach
#foreach($directoryInfo->images as $index => $image)
<li class='list-inline-item {{ $index + sizeof($directoryInfo->videos) === 0 ? 'active' : '' }}'>
<a id='carousel-selector-{{ $index + sizeof($directoryInfo->videos) }}' data-slide-to='{{ $index + sizeof($directoryInfo->videos) }}' data-target='#sme-directory-gallery'>
<img src='{{ asset('storage/' . $image->path) }}' class='img-fluid'>
</a>
</li>
#endforeach
</ul>
</div>
</div>
Javascript:
$(document).ready(function () {
$('.carousel-indicators').scrollLeft(0);
$('#sme-directory-gallery').carousel();
$('.pause-carousel').on('click', function () {
$('#sme-directory-gallery').carousel('pause'); // it works
});
$('.pause-carousel-2').on('click', function () {
$('#sme-directory-gallery').carousel('pause'); // it wont work
});
$('#sme-directory-gallery .video-mask').mouseup(function () {
var iframe = $(this).closest('.item').find('iframe');
var iframe_source = iframe.attr('src');
if (iframe_source.includes('?rel=0')) {
iframe_source = iframe_source.replace('?rel=0', '');
}
iframe_source = iframe_source + '?autoplay=1';
iframe.attr('src', iframe_source);
$(this).toggle();
$('#sme-directory-gallery').carousel('pause');
});
$('#sme-directory-gallery').on('slide.bs.carousel', function (e) {
$('#sme-directory-gallery').carousel('cycle');
var iframeID = $(this).find('iframe').attr('id');
if (iframeID != undefined) {
callPlayer(iframeID, 'stopVideo');
}
$('.video-mask').show();
$('#sme-directory-gallery').find('iframe').each(function (key, value) {
var url = $(this).attr('src');
if (url.includes('?autoplay')) {
var new_url = url.substring(0, url.indexOf('?'));
$(this).attr('src', new_url);
}
});
setTimeout(() => {
var scrollTo = $('.list-inline-item.active').position().left;
if ($('.list-inline-item.active').index() > 0) {
scrollTo = $('.list-inline-item.active').prev('.list-inline-item').position().left;
}
var finalOrFirst = 0;
if (e.direction === 'right') {
if ($('.list-inline-item.active').is(':last-child')) {
finalOrFirst = 99999;
}
} else {
if ($('.list-inline-item.active').is(':first-child')) {
finalOrFirst = -99999;
}
}
var currentScroll = $('.carousel-indicators').scrollLeft();
var scrollResult = currentScroll + scrollTo + finalOrFirst;
$('.carousel-indicators').animate({scrollLeft: scrollResult}, 500);
}, 10);
});
});
What exactly is happening here, how do I fix it?
Thanks in advance.
Try this to catch the issue:
Put console.log or alert() to check if event is triggered or not.
$('.pause-carousel-2').on('click', function () {
console.log('Button Clicked');
$('#sme-directory-gallery').carousel('pause'); // it wont work
});
Case 1:
If "Button Click" is not printed in console, then you may try:
$('body').on('click','.pause-carousel-2',function(){ ...
Case 2:
If "Button Click" is printed, then there is a workaround for this issue, which you can try.
Use Trigger
$('.pause-carousel-2').on('click', function () {
$('.pause-carousel').trigger("click");
});
and hide the Pause button which is outside
Please share your result, will try to fix your issue.
If you use .carousel() as a varaible it will work. var slider = $('#element').carousel(); And you can use in all events. slider.carousel('pause'); , for starting again: slider.carousel({'pause': false});
When you use multiple element click events:
$('#btn1, #btn2').click(function(){
slider.carousel('pause');
});
In an another event (hover):
$('#yourSlider').hover(function(){
slider.carousel('pause');
}, function(){
slider.carousel({'pause': false});
});
If you don't assign it to a variable, the carousel will be restarted
within each event.
I added an examp (it works):
$(function(){
var slider = $('#carouselExampleSlidesOnly').carousel({
interval: 1000
});
$('#pause').click(function(){
slider.carousel('pause');
});
$('#start').click(function(){
slider.carousel({'pause': false});
});
});
.carousel-item{
padding-top: 45px;
text-align: center;
height:150px;
width:100%;
color:#fff;
background-color: #666;
font-size: 2rem;
font-weight: 700;
}
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"/>
<div class="container p-4">
<button id="pause" class="btn btn-sm btn-warning">Pause</button>
<button id="start" class="ml-2 btn btn-sm btn-primary">Start</button>
</div>
<div id="carouselExampleSlidesOnly" class="carousel slide" data-ride="carousel" style="width: 90%; marign:auto">
<div class="carousel-inner">
<div class="carousel-item active">
Slide 1
</div>
<div class="carousel-item">
Slide 2
</div>
<div class="carousel-item">
Slide 3
</div>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
Set the pause to false and that will take care of the issue
$('.carousel').carousel({
pause: "false"
});
you can see an example here: https://jsfiddle.net/KyleMit/XFcSv/
I have a problem similar to this one: in some case the code doesn't work in some case works. The only difference I have found is about the presence of the class "pointer-event" in the tag of the carousel element.
To solve this problem I have use a boolean variable with the event "slide.bs.carousel" to avoid carousel to slide when paused.
HTML CODE
<section id="slideshow" class="carousel slide">
<div class="carousel-inner" id="images" >
<div class="carousel-item " >
<img src="..." class="d-block w-100" alt='bla bla bla' >
</div>
<div class="carousel-item " >
<img src="..." class="d-block w-100" alt='bla bla bla' >
</div>
<div class="carousel-item " >
<img src="..." class="d-block w-100" alt='bla bla bla' >
</div>
</div>
<a class="carousel-control-pause" href="#slideshow" role="button" >
<span class="pause-icon">
||
</span>
<span class="play-icon d-none">
|>
</span>
</a>
<a class="carousel-control-prev" href="#slideshow" role="button" data-slide="prev" >
<--
</a>
<a class="carousel-control-next" href="#slideshow" role="button" data-slide="next" >
-->
</a>
</section>
JAVASCRIPT CODE
$(document).ready(function(){
var carousel = $('#slideshow').carousel({
interval: 5000,
ride: true
});
var carousel_paused = false;
//on init the carousel is paused
$('#slideshow .carousel-control-pause').on('click', function(e){
e.preventDefault();
var hideclass= "d-none";
var pause= $(this).children(".pause-icon");
if( $(pause).is(":hidden"))
{
//play
$(pause).removeClass(hideclass);
$(this).children(".play-icon").addClass(hideclass);
carousel.carousel('cycle');
carousel_paused = false;
}
else
{
//pause
$(pause).addClass(hideclass);
$(this).children(".play-icon").removeClass(hideclass);
carousel.carousel('pause');
carousel_paused = true;
}
});
carousel.on('slide.bs.carousel', function (e) {
console.log("slide pre");
//prevent slide if paused
if(carousel_paused)
e.preventDefault();
});
carousel.on('slid.bs.carousel', function (e) {
console.log("slide done");
});
});
The code is for example and is not tested in mobile.

Adding autoplay + prev&next buttons to slider

im using the slider explained in codrops tutorial http://tympanus.net/codrops/2014/03/13/tilted-content-slideshow/comment-page-2/#comment-458990.
It uses a simple ordered list to display the slides:
<div class="slideshow" id="slideshow">
<ol class="slides">
<li class="current">
<div class="description">
<h2>Slide 1 Title</h2>
<p>Slide 1 content</p>
</div>
<div class="tiltview col">
<img src="img/1_screen.jpg"/>
<img src="img/2_screen.jpg"/>
</div>
</li>
<li>
<div class="description">
<h2>Slide 2 title</h2>
<p>Slide 2 content</p>
</div>
<div class="tiltview row">
<img src="img/3_mobile.jpg"/>
<img src="img/4_mobile.jpg"/>
</div>
</li>
</ol>
</div><!-- /slideshow -->
Then a navigation is created using javascript, this navigation display a set of that when clicked they display the slides:
TiltSlider.prototype._addNavigation = function() {
// add nav "dots"
this.nav = document.createElement( 'nav' )
var inner = '';
for( var i = 0; i < this.itemsCount; ++i ) {
inner += i === 0 ? '<span class="current"></span>' : '<span></span>';
}
this.nav.innerHTML = inner;
this.el.appendChild( this.nav );
this.navDots = [].slice.call( this.nav.children );
}
TiltSlider.prototype._initEvents = function() {
var self = this;
// show a new item when clicking the navigation "dots"
this.navDots.forEach( function( dot, idx ) {
dot.addEventListener( 'click', function() {
if( idx !== self.current ) {
self._showItem( idx );
}
} );
} );
}
It all works fine but does anybody have any idea of how could I add autoplay and prev&next buttons to this slider??
You can create the autoplay function manually by using jquery. My code will call the each slide after 10 seconds. (i.e) the next slider will called after 10 seconds
$(document).ready(function(){
new TiltSlider( document.getElementById( 'slideshow' ) );
window.setInterval(function(){
$('nav>.current').next().trigger('click');
if($('nav > .current').next().index() == '-1'){
$('nav > span').trigger('click');
}
}, 10000);
});

Accordion with javascript

I've been trying to get an accordion movement going with javascript.
The problem that I'm having is having one close if it's already open and stay closed.
Right now the according closing one and opening another when I click a different div.
I see that the argument is always resolving to true because I'm removing the classes.. but I can't seem to find a away to get around that so I could have a nice accordion.
<div class="speaker-container">
<div class="span3 offset1 speaker" id="sp-info-0">
<div class="speaker-img">
<div class="hover"></div>
<img src="" alt="">
</div>
<h4>Title</h4>
</div>
<div class="speaker-info" id="sp-info-0">
<button class="close-speaker">Close</button>
<h2>Title</h2>
</div>
<div class="span3 offset1 speaker" id="sp-info-1">
<div class="speaker-img">
<div class="hover"></div>
<img src="" alt="">
</div>
<h4>Sub Title</h4>
</div>
<div class="speaker-info" id="sp-info-1">
<button class="close-speaker">Close</button>
<h2>Title</h2>
</div>
<div class="span3 offset1 speaker" id="sp-info-2">
<div class="speaker-img">
<div class="hover"></div>
<img src="" alt="">
</div>
<h4>Title</h4>
</div>
<div class="speaker-info" id="sp-info-2">
<button class="close-speaker">Close</button>
<h2>Title</h2>
</div>
</div>
var timer;
$('.speaker-container .speaker').on('click', function(){
var speakerContainer = document.getElementsByClassName('speaker-container');
var self = this;
var children = $('.speaker-container').children();
var selfHeight = this.clientHeight;
var parentOffset = this.parentElement.offsetHeight;
var selfOffset = this.nextElementSibling.offsetHeight;
console.dir(children);
console.log(parentOffset);
$('.speaker-container').removeClass('open').css({'height' : selfHeight + 'px'});
for (var i = 0; i < children.length; i++) {
if (children[i].className == 'speaker-info fade') {
console.dir(children[i]);
$(children[i]).removeClass('fade');
}
}
if (self.parentElement.className !== 'speaker-container open' && self.nextElementSibling.className !== 'speaker-info fade') {
timer = setTimeout(function(){
self.parentElement.setAttribute('class' , 'speaker-container open');
self.parentElement.style.height = selfOffset + selfHeight + 'px';
self.nextElementSibling.style.top = selfHeight + 'px';
self.nextElementSibling.setAttribute('class' , 'speaker-info fade');
// return false;
}, 500);
} else {
$('.speaker-container').removeClass('open').css({'height' : selfHeight + 'px'});
self.nextElementSibling.setAttribute('class' , 'speaker-info');
window.clearTimeout(timer);
}
});
Make a class that has the item open. (let's say the class is "open")
Make a class that has the item closed. (let's say the class is closed")
let's say all the accordion items are in the accordion class.
function that opens an item:
cycle through and remove any existing open item classes, add closed class.
add open class to the selected item.
by default, give closed class to all items (except the one you want open by default, if any)
with javascript it would look something like:
function openOnClick()
{
var openaccordion=document.getElementsByClassName('open');
openaccordion.className.replace( /(?:^|\s)open(?!\S)/g , 'close' );
this.className.replace( /(?:^|\s)close(?!\S)/g , 'open' );
}
with jQuery it would look like this:
$('div.accordion').click(function(){
$('.open').removeClass('open').addClass('close');
$(this).removeClass('close').addClass('open');
}
you can use jqueryui to get some sliding effects in there pretty simply too:
$(this).switchClass('close','open',1000);

Combine two collections of elements with mobify.js

everyone.
I've just started using the mobifyjs toolkit and I've ran into a problem of combining two collections of elements into one.
On a page I'm trying to mobify there are two sets of links: with text and images. The HTML looks like the following:
<!-- links with text -->
<div id="products">
Product 1
Product 2
</div>
...
<!-- somewhere else on the page -->
<div id="productImages">
<img src="Product1.png />
<img src="Product2.png />
</div>
It needs to turn into the following:
<div class="items">
<div class="item">
<div class="img">
<img src="Product1.png />
</div>
<div class="title">
Product 1
</div>
</div>
<div class="item">
<div class="img">
<img src="Product2.png />
</div>
<div class="title">
Product 2
</div>
</div>
</div>
My current solution is to use map function, so in the mobify.konf I have something like the following:
'content': function(context) {
return context.choose(
{{
'templateName': 'products',
'products': function(){
return $('#productImages a').map(function() {
var href = $(this).attr('href') || '';
var div = $('<div class="item"><div class="img"></div><div class="title"></div></div>');
div.find('.img').append($(this).clone());
div.find('.title').append($('#products a[href="' + href + '"]').clone());
return div;
});
}
})
}
And the template is:
<div class="items">
{#content.products}
{.}
{/content.products}
</div>
This code does work but the approach itself is pretty ugly since I have to move a piece of markup code from the tmpl file into mobify.konf. Can anyone suggest a better solution?
The best way to do this sort of thing is to collect the relevant properties for your items (e.g. the product name, the image url and the link href) into a data structure in javascript, and then create a template for your new html structure in the .tmpl file. Something like
'products': function() {
var products = [],
$productLinks = $('#products a'),
$productImages = $('#productImages img')
len = $productNames.legnth;
for(var i = 0; i<len; i++) {
var $link = $productLinks.eq(i);
var $img = $productImages.eq(i);
products.push({name: $link.text(), href: $link.attr('href'), imgSrc: $img.attr('src')});
}
return products;
}
and then template it by iterating over the array items and inserting them into relevant places in the markup:
<div class="items">
{#content.products}
<div class="item">
<div class="img"><img src="{.imgSrc}" /></div>
<div class="title">{.name}</div>
</div>
{content.products}
</div>

jQuery Newbie, need a little help

Okay, so I am in the process of recreating this feature:
http://www.w3.org/html/logo/#the-technology
I current have it so when you click on a link, it will add a class to the image that relates to that link (href="#one" on the <a> and then id="#one" on the <img>), however it is currently not going through each <a> tag and only one. And also it is not removing the class I requested.
Code follows:
JS
$(document).ready(function() {
var container = '#portfolio #text_container';
var img_container = '#portfolio #image_container';
$(container).children('a').bind('click', function() {
var this_attr = $(this).attr('href');
var this_img = $(img_container).find('img').attr('id');
if(this_attr == this_img) {
//$(img_container).find('img').hasClass('current').removeClass('current');
// ^^^ This line isn't working, any ideas? :/
$(img_container + ' img[id*="' + this_attr + '"]').addClass('current');
}
else {
alert(this_img + ' this img');
alert(this_attr + ' this attr');
}
});
});
And the HTML is as follows
<div id="portfolio">
<div id="image_container">
<img src="http://static.jquery.com/files/rocker/images/logo_jquery_215x53.gif" alt="" class="current" id="#one" />
<img src="http://static.jquery.com/files/rocker/images/btn_downloadLarge.gif" alt="" id="#two" />
</div>
<div id="text_container">
Item 1
Item 2
<p id="#one" class="current">A bunch of text!</p>
<p id="#two">The second bunch of text!</p>
</div>
</div>
Please let me know if you need any more information :)
rcravens fixed this with the following code..
JS
$(document).ready(function() {
$('#text_container a').click(function(evt) {
evt.preventDefault();
$('.current').removeClass('current');
var href = $(this).attr('href');
$("." + href).addClass('current');
});
And the HTML..
<div id="portfolio">
<div id="image_container">
<img src="http://static.jquery.com/files/rocker/images/logo_jquery_215x53.gif" alt="" class="one current" />
<img src="http://static.jquery.com/files/rocker/images/btn_downloadLarge.gif" alt="" class="two" />
</div>
<div id="text_container">
Item 1
Item 2
<p class="one current">A bunch of text!</p>
<p class="two">The second bunch of text!</p>
</div>
</div>
My interpretation of what you are trying to do is here:
http://jsfiddle.net/rcravens/wMhEC/
The code is changed a bit. You shouldn't have multiple elements with the same id.
Bob
The reason this isn't working:
if(this_attr == this_img)
is because this_attr is a URL and this_img is an ID attribute value.

Categories

Resources