I have a simple project based on one variation of fullpage script. Everything works perfect except for one annoying thing - I can't understand how to make my right navigation bullets clickable (to an appropriate section). My js knowledge is not too good at the moment so I'd really appreciate any help, guys. Thanks!
$.fullPage = function(option) {
var defaultOpt = {
box: "#fullPageBox", // 滚屏页父元素
page: ".fullPage", // 滚屏页面
index: true, // 是否显示索引
duration: 1000, // 动画时间
direction: "vertical", // 滚屏方向 horizontal or vertical
loop: true // 是否循环
},
This = this,
index = 0,
over = true;
this.option = $.extend({}, defaultOpt, option || {});
this.box = $(this.option.box);
this.pages = $(this.option.page);
this.duration = this.option.duration;
// 绑定鼠标滚轮事件
$(document).on("mousewheel DOMMouseScroll", function(ev) {
var dir = ev.originalEvent.wheelDelta || -ev.originalEvent.detail;
if (over === false) return;
dir < 0 ? nextPage() : prevPage();
});
if (this.option.index) {
initPagination();
};
function initPagination() {
var oUl = $("<ul id='fullPageIndex'></ul>"),
liStr = "";
for (var i = 0, len = This.pages.length; i < len; i++) {
liStr += "<li></li>";
};
$(document.body).append(oUl.append($(liStr)));
$("#fullPageIndex li").eq(index).addClass("active").siblings().removeClass("active");
};
function nextPage() {
if (index < This.pages.length - 1) {
index++;
} else {
index = 0;
}
scrollPage(index, This.pages.eq(index).position());
};
function prevPage() {
if (index === 0) {
index = This.pages.length - 1;
} else {
index--;
}
scrollPage(index, This.pages.eq(index).position());
};
function scrollPage(index, position) {
over = false;
var cssStr = This.option.direction === "vertical" ? {
top: -position.top
} : {
left: -position.left
};
This.box.animate(cssStr, This.duration, function() {
over = true;
})
$("#fullPageIndex li").eq(index).addClass("active").siblings().removeClass("active");
};
}
* {
margin: 0;
padding: 0;
}
html,
body {
height: 100%;
overflow: hidden;
}
.pageBox {
position: relative;
height: 100%;
}
.main {
width: 100%;
height: 500%;
min-width: 1200px;
position: absolute;
left: 0;
top: 0;
color: #fff;
}
.main .fullPage {
height: 25%;
}
.bg1 {
background-color: #27AE60;
}
.bg2 {
background-color: #3498DB;
}
.bg3 {
background-color: #C0392B;
}
.bg4 {
background-color: #4FC2E5;
}
.bg5 {
background-color: #8E44AD;
}
#fullPageIndex {
position: absolute;
top: 50%;
right: 20px;
transform: translateY(-50%);
}
#fullPageIndex li {
width: 10px;
height: 10px;
list-style: none;
background-color: black;
margin: 6px 0;
border-radius: 50%;
}
#fullPageIndex li.active {
background-color: white;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>
<div class="pageBox">
<div class="main" id="fullPageBox">
<div class="fullPage bg1">jQuery fullPage.js</div>
<div class="fullPage bg2">Section 2</div>
<div class="fullPage bg3">Section 3</div>
<div class="fullPage bg4">Section 4</div>
<div class="fullPage bg5">Section 5</div>
</div>
</div>
<script>
$.fullPage();
</script>
</body>
Add an id attribute to you divs and add an anchor to the list elements that navigate to the desired sections. As follows:
<body>
<div class="pageBox">
<div class="main" id="fullPageBox">
<div id="section1" class="fullPage bg1">jQuery fullPage.js</div>
<div id="section2" class="fullPage bg2">Section 2</div>
<div id="section3" class="fullPage bg3">Section 3</div>
<div id="section4" class="fullPage bg4">Section 4</div>
<div id="section5" class="fullPage bg5">Section 5</div>
</div>
</div>
<script>
$.fullPage();
</script>
</body>
Update your js where you render the list items to look like this:
function initPagination() {
var oUl = $("<ul id='fullPageIndex'></ul>"),
liStr = "";
for (var i = 0, len = This.pages.length; i <= len; i++) {
var sectionNum = i + 1;
liStr += '<li></li>';
};
$(document.body).append(oUl.append($(liStr)));
$("#fullPageIndex li").eq(index).addClass("active").siblings().removeClass("active");
};
Read more here
EDIT:
Since you asked for a smooth scroll as well you could add this to your JS:
$('a[href*=#]:not([href=#])').click(function() {
if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'')
|| location.hostname == this.hostname) {
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
if (target.length) {
$('html,body').animate({
scrollTop: target.offset().top
}, 1000);
return false;
}
}
});
Source for the snippet can be found on this page.
there is some mistake in your script.
First, remove below code from your HTML file:
<script>
fullPage();
</script>
Second is, you've created wrong function (method) define. I'am replace $.fullpage = function(option) { with var fullpage = function(options) {
and for the last is: since we have removed your fullpage() initiator, so we need to call this method again. for example at end line of your JS file,
P.S:
In Javascript you can create function in several ways. See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions for more detail.
See fixed code below:
var fullPage = function(option) {
var defaultOpt = {
box: "#fullPageBox", // 滚屏页父元素
page: ".fullPage", // 滚屏页面
index: true, // 是否显示索引
duration: 1000, // 动画时间
direction: "vertical", // 滚屏方向 horizontal or vertical
loop: true // 是否循环
},
This = this,
index = 0,
over = true;
this.option = $.extend({}, defaultOpt, option || {});
this.box = $(this.option.box);
this.pages = $(this.option.page);
this.duration = this.option.duration;
// 绑定鼠标滚轮事件
$(document).on("mousewheel DOMMouseScroll", function(ev) {
var dir = ev.originalEvent.wheelDelta || -ev.originalEvent.detail;
if (over === false) return;
dir < 0 ? nextPage() : prevPage();
});
if (this.option.index) {
initPagination();
};
function initPagination() {
var oUl = $("<ul id='fullPageIndex'></ul>"),
liStr = "";
for (var i = 0, len = This.pages.length; i < len; i++) {
liStr += "<li></li>";
};
$(document.body).append(oUl.append($(liStr)));
$("#fullPageIndex li").eq(index).addClass("active").siblings().removeClass("active");
};
function nextPage() {
if (index < This.pages.length - 1) {
index++;
} else {
index = 0;
}
scrollPage(index, This.pages.eq(index).position());
};
function prevPage() {
if (index === 0) {
index = This.pages.length - 1;
} else {
index--;
}
scrollPage(index, This.pages.eq(index).position());
};
function scrollPage(index, position) {
over = false;
var cssStr = This.option.direction === "vertical" ? {
top: -position.top
} : {
left: -position.left
};
This.box.animate(cssStr, This.duration, function() {
over = true;
})
$("#fullPageIndex li").eq(index).addClass("active").siblings().removeClass("active");
};
}
fullPage();
* {
margin: 0;
padding: 0;
}
html,
body {
height: 100%;
overflow: hidden;
}
.pageBox {
position: relative;
height: 100%;
}
.main {
width: 100%;
height: 500%;
min-width: 1200px;
position: absolute;
left: 0;
top: 0;
color: #fff;
}
.main .fullPage {
height: 25%;
}
.bg1 {
background-color: #27AE60;
}
.bg2 {
background-color: #3498DB;
}
.bg3 {
background-color: #C0392B;
}
.bg4 {
background-color: #4FC2E5;
}
.bg5 {
background-color: #8E44AD;
}
#fullPageIndex {
position: absolute;
top: 50%;
right: 20px;
transform: translateY(-50%);
}
#fullPageIndex li {
width: 10px;
height: 10px;
list-style: none;
background-color: black;
margin: 6px 0;
border-radius: 50%;
}
#fullPageIndex li.active {
background-color: white;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<body>
<div class="pageBox">
<div class="main" id="fullPageBox">
<div class="fullPage bg1">jQuery fullPage.js</div>
<div class="fullPage bg2">Section 2</div>
<div class="fullPage bg3">Section 3</div>
<div class="fullPage bg4">Section 4</div>
<div class="fullPage bg5">Section 5</div>
</div>
</div>
</body>
Related
Using the tags() function, there is a parameter for maximum number of tags (maxTags) you can enter into each input.
I need to hide(); the tags-input when maxTags = 2 and then
show(); when the tag is removed / not at the max.
maxTags :1 isn't working but it should be. Only 2 or more is acceptable. I tried debugging the max tags parameter but couldn't find out why maxTags: 1 is
unacceptable.
How can I change the function to allow maxTags: 1 and also show/hide the tag-input when maxTags is reached?
// max tags in tags() function:
if (opts.maxTags) {
if ($self.val().split(",").length == opts.maxTags) {
otherCheck = false;
$input.val("");
$next.val("");
}
}
// Calling the tags() function:
$("#" + formId)
.find(".input--proj")
.tags({
unique: true,
maxTags: 2
})
.autofill({
data: autolist
});
(function($) {
$.fn.tags = function(opts) {
var selector = this.selector;
//console.log("selector",selector);
// updates the original input
function update($original) {
var all = [];
var list = $original.closest(".tags-wrapper").find("li.tag span").each(function() {
all.push($(this).text());
});
all = all.join(",");
$original.val(all);
}
return this.each(function() {
var self = this,
$self = $(this),
$wrapper = $("<div class='tags-wrapper'><ul></ul></div");
tags = $self.val(),
tagsArray = tags.split(","),
$ul = $wrapper.find("ul");
// make sure have opts
if (!opts) opts = {};
opts.maxSize = 50;
// add tags to start
tagsArray.forEach(function(tag) {
if (tag) {
$ul.append("<li class='tag'><span>" + tag + "</span><a href='#'>x</a></li>");
}
});
// get classes on this element
if (opts.classList) $wrapper.addClass(opts.classList);
// add input
$ul.append("<li class='tags-input'><input type='text' class='tags-secret'/></li>");
// set to dom
$self.after($wrapper);
// add the old element
$wrapper.append($self);
// size the text
var $input = $ul.find("input"),
size = parseInt($input.css("font-size")) - 4;
// delete a tag
$wrapper.on("click", "li.tag a", function(e) {
e.preventDefault();
$(this).closest("li").remove();
$self.trigger("tagRemove", $(this).closest("li").find("span").text());
update($self);
$("[data-search]").keyup();
});
// backspace needs to check before keyup
$wrapper.on("keydown", "li input", function(e) {
// backspace
if (e.keyCode == 8 && !$input.val()) {
var $li = $ul.find("li.tag:last").remove();
update($self);
$self.trigger("tagRemove", $li.find("span").text());
}
// prevent for tab
if (e.keyCode == 9) {
e.preventDefault();
}
});
// as we type
$wrapper.on("keyup", "li input", function(e) {
e.preventDefault();
$ul = $wrapper.find("ul");
var $next = $input.next(),
usingAutoFill = $next.hasClass("autofill-bg"),
$inputLi = $ul.find("li.tags-input");
// regular size adjust
$input.width($input.val().length * (size));
// if combined with autofill, check the bg for size
if (usingAutoFill) {
$next.width($next.val().length * (size));
$input.width($next.val().length * (size));
// make sure autofill doesn't get too big
if ($next.width() < opts.maxSize) $next.width(opts.maxSize);
var list = $next.data().data;
}
// make sure we don't get too high
if ($input.width() < opts.maxSize) $input.width(opts.maxSize);
// tab, comma, enter
if (!!~[9, 188, 13].indexOf(e.keyCode)) {
var val = $input.val().replace(",", "");
var otherCheck = true;
// requring a tag to be in autofill
if (opts.requireData && usingAutoFill) {
if (!~list.indexOf(val)) {
otherCheck = false;
$input.val("");
}
}
// unique
if (opts.unique) {
// found a match already there
if (!!~$self.val().split(",").indexOf(val)) {
otherCheck = false;
$input.val("");
$next.val("");
}
}
// max tags
if (opts.maxTags) {
if ($self.val().split(",").length == opts.maxTags) {
otherCheck = false;
$input.val("");
$next.val("");
}
}
// if we have a value, and other checks pass, add the tag
if (val && otherCheck) {
// place the new tag
$inputLi.before("<li class='tag'><span>" + val + "</span><a href='#'>x</a></li>");
// clear the values
$input.val("");
if (usingAutoFill) $next.val("");
update($self);
$self.trigger("tagAdd", val);
}
}
});
});
}
})(jQuery);
var uniqueId = 1;
$(function() {
$(".btn--new").click(function() {
var copy = $("#s_item").clone(true, true);
var formId = "item_" + uniqueId;
copy.attr("id", formId);
$("#s_list").append(copy);
$("#" + formId)
.find(".input--proj")
.each(function() {
var autolist = new Array();
$.each($(".studio__project"), function(index, value) {
if ($.inArray($(value).attr("data-proj"), autolist) < 1) {
autolist.push($(value).attr("data-proj").toLowerCase());
}
});
$("#" + formId)
.find(".input--proj")
.tags({
unique: true,
maxTags: 2
})
.autofill({
data: autolist
});
function placeholderproj() {
$(".search__label--proj")
.find(".tags-secret")
.attr("placeholder", "Enter Keyword");
}
$(document).ready(placeholderproj);
});
uniqueId++;
});
});
$(document).on("keyup , keypress", "li input", function(e) {
$.each($(".tag"), function(index, value) {
$.each($(".studio__project"), function(subIndex, subValue) {
if (
$(subValue).attr("data-proj").toLowerCase() ==
$(value).find("span").html()
) {
var itemColor = $(subValue).attr("data-color");
$(value).css("background-color", itemColor);
}
});
});
$("[data-search]").keyup();
});
$(document).on("click", ".tag a", function(e) {
$("[data-search]").keyup();
});
$(document).ready(function() {
$(".btn--new").trigger("click");
$(".btn--new").trigger("click");
$(".btn--new").trigger("click");
});
::-webkit-input-placeholder {
/* Chrome/Opera/Safari */
color: #8e8e8e;
}
::-moz-placeholder {
/* Firefox 19+ */
color: #8e8e8e;
}
:-ms-input-placeholder {
/* IE 10+ */
color: #8e8e8e;
}
:-moz-placeholder {
/* Firefox 18- */
color: #8e8e8e;
}
.tags-wrapper {
background: white;
display: flex;
position: relative;
width: 100%;
height: 50px;
top: -1px;
border: 1px solid whitesmoke;
overflow: hidden;
}
.tags-wrapper ul {
position: absolute;
display: flex;
flex: 1;
align-items: center;
top: 0;
bottom: 0;
right: 0;
left: 0;
list-style-type: none;
margin: 0;
padding: 0;
}
.tags-wrapper li {
flex-grow: 1;
margin-left: 5px;
}
.tags-wrapper li input {
display: block;
border: none;
width: 100% !important;
}
.tags-wrapper li.tag {
display: flex;
flex-grow: 0;
position: relative;
padding: 10px;
font-size: 14px;
align-items: center;
border-radius: 5px;
list-style: none;
background-image: none;
box-shadow: none;
color: white;
}
.tags-wrapper li a {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
text-decoration: none;
color: rgba(0, 0, 0, 0);
}
.tags-wrapper li a:hover {
background-color: rgba(0, 0, 0, 0.4);
border-radius: 5px;
color: rgba(0, 0, 0);
background-image: url("http://svgshare.com/i/3yv.svg");
background-size: contain;
background-repeat: no-repeat;
background-position: center;
}
.tags-wrapper input {
display: none;
}
#s_item {
display: none
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.staticaly.com/gh/moofawsaw/donorport/master/auto-fill.min.js"></script>
<a id="btn_studio" href="#" class="btn btn--new ripple w-button">Create</a>
<div>keywords are: blue, red, green</div>
<div id="s_list">
<div id="s_item" data-item="studio" data-mode="none" class="post__item studio__item">
<div data-item="studio" class="post__itemwrap post__itemwrap--studio">
<div class="search search--proj w-embed"><label class="search__label--proj" data-color="">
<input type="text" class="input--proj" autocomplete="off" placeholder="">
</label></div>
<div class="w-dyn-list">
<div class="w-dyn-items">
<div class="w-dyn-item">
<div class="w-embed">
<div class="studio__project" data-proj="Blue" data-color="blue"></div>
</div>
</div>
<div class="w-dyn-item">
<div class="w-embed">
<div class="studio__project" data-proj="Green" data-color="green"></div>
</div>
</div>
<div class="w-dyn-item">
<div class="w-embed">
<div class="studio__project" data-proj="Red" data-color="red"></div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
I've added code to test maxTags value from 1 to 3. Just replace it.
Removed a tag. Show input.
$wrapper.on("click", "li.tag a", function(e) {
e.preventDefault();
$(this).closest("li").remove();
$self.trigger("tagRemove", $(this).closest("li").find("span").text());
update($self);
$("[data-search]").keyup();
$input.show(); // show input on remove
});
If string has no content, return 0. Else use split to find number of elements.
if (opts.maxTags) {
var len = $self.val();
len = len.trim().length > 0 ? len.split(',').length : 0;
(function($) {
$.fn.tags = function(opts) {
var selector = this.selector;
//console.log("selector",selector);
// updates the original input
function update($original) {
var all = [];
var list = $original.closest(".tags-wrapper").find("li.tag span").each(function() {
all.push($(this).text());
});
all = all.join(",");
$original.val(all);
}
return this.each(function() {
var self = this,
$self = $(this),
$wrapper = $("<div class='tags-wrapper'><ul></ul></div");
tags = $self.val(),
tagsArray = tags.split(","),
$ul = $wrapper.find("ul");
// make sure have opts
if (!opts) opts = {};
opts.maxSize = 50;
// add tags to start
tagsArray.forEach(function(tag) {
if (tag) {
$ul.append("<li class='tag'><span>" + tag + "</span><a href='#'>x</a></li>");
}
});
// get classes on this element
if (opts.classList) $wrapper.addClass(opts.classList);
// add input
$ul.append("<li class='tags-input'><input type='text' class='tags-secret'/></li>");
// set to dom
$self.after($wrapper);
// add the old element
$wrapper.append($self);
// size the text
var $input = $ul.find("input"),
size = parseInt($input.css("font-size")) - 4;
// delete a tag
$wrapper.on("click", "li.tag a", function(e) {
e.preventDefault();
$(this).closest("li").remove();
$self.trigger("tagRemove", $(this).closest("li").find("span").text());
update($self);
$("[data-search]").keyup();
$input.show(); // show input on remove
});
// backspace needs to check before keyup
$wrapper.on("keydown", "li input", function(e) {
// backspace
if (e.keyCode == 8 && !$input.val()) {
var $li = $ul.find("li.tag:last").remove();
update($self);
$self.trigger("tagRemove", $li.find("span").text());
}
// prevent for tab
if (e.keyCode == 9) {
e.preventDefault();
}
});
// as we type
$wrapper.on("keyup", "li input", function(e) {
e.preventDefault();
$ul = $wrapper.find("ul");
var $next = $input.next(),
usingAutoFill = $next.hasClass("autofill-bg"),
$inputLi = $ul.find("li.tags-input");
// regular size adjust
$input.width($input.val().length * (size));
// if combined with autofill, check the bg for size
if (usingAutoFill) {
$next.width($next.val().length * (size));
$input.width($next.val().length * (size));
// make sure autofill doesn't get too big
if ($next.width() < opts.maxSize) $next.width(opts.maxSize);
var list = $next.data().data;
}
// make sure we don't get too high
if ($input.width() < opts.maxSize) $input.width(opts.maxSize);
// tab, comma, enter
if (!!~[9, 188, 13].indexOf(e.keyCode)) {
var val = $input.val().replace(",", "");
var otherCheck = true;
// requring a tag to be in autofill
if (opts.requireData && usingAutoFill) {
if (!~list.indexOf(val)) {
otherCheck = false;
$input.val("");
}
}
// unique
if (opts.unique) {
// found a match already there
if (!!~$self.val().split(",").indexOf(val)) {
otherCheck = false;
$input.val("");
$next.val("");
}
}
// max tags
if (opts.maxTags) {
var len = $self.val();
len = len.trim().length > 0 ? len.split(',').length : 0;
if (len == opts.maxTags - 1) $input.hide();
if (len == opts.maxTags) {
otherCheck = false;
$input.val("");
$next.val("");
}
}
// if we have a value, and other checks pass, add the tag
if (val && otherCheck) {
// place the new tag
$inputLi.before("<li class='tag'><span>" + val + "</span><a href='#'>x</a></li>");
// clear the values
$input.val("");
if (usingAutoFill) $next.val("");
update($self);
$self.trigger("tagAdd", val);
}
}
});
});
}
})(jQuery);
var uniqueId = 1;
$(function() {
$(".btn--new").click(function() {
var copy = $("#s_item").clone(true, true);
var formId = "item_" + uniqueId;
copy.attr("id", formId);
$("#s_list").append(copy);
$("#" + formId)
.find(".input--proj")
.each(function() {
var autolist = new Array();
$.each($(".studio__project"), function(index, value) {
if ($.inArray($(value).attr("data-proj"), autolist) < 1) {
autolist.push($(value).attr("data-proj").toLowerCase());
}
});
$("#" + formId)
.find(".input--proj")
.tags({
unique: true,
maxTags: 1
})
.autofill({
data: autolist
});
function placeholderproj() {
$(".search__label--proj")
.find(".tags-secret")
.attr("placeholder", "Enter Keyword");
}
$(document).ready(placeholderproj);
});
uniqueId++;
});
});
$(document).on("keyup , keypress", "li input", function(e) {
$.each($(".tag"), function(index, value) {
$.each($(".studio__project"), function(subIndex, subValue) {
if (
$(subValue).attr("data-proj").toLowerCase() ==
$(value).find("span").html()
) {
var itemColor = $(subValue).attr("data-color");
$(value).css("background-color", itemColor);
}
});
});
$("[data-search]").keyup();
});
$(document).on("click", ".tag a", function(e) {
$("[data-search]").keyup();
});
$(document).ready(function() {
$(".btn--new").trigger("click");
$(".btn--new").trigger("click");
$(".btn--new").trigger("click");
});
::-webkit-input-placeholder {
/* Chrome/Opera/Safari */
color: #8e8e8e;
}
::-moz-placeholder {
/* Firefox 19+ */
color: #8e8e8e;
}
:-ms-input-placeholder {
/* IE 10+ */
color: #8e8e8e;
}
:-moz-placeholder {
/* Firefox 18- */
color: #8e8e8e;
}
.tags-wrapper {
background: white;
display: flex;
position: relative;
width: 100%;
height: 50px;
top: -1px;
border: 1px solid whitesmoke;
overflow: hidden;
}
.tags-wrapper ul {
position: absolute;
display: flex;
flex: 1;
align-items: center;
top: 0;
bottom: 0;
right: 0;
left: 0;
list-style-type: none;
margin: 0;
padding: 0;
}
.tags-wrapper li {
flex-grow: 1;
margin-left: 5px;
}
.tags-wrapper li input {
display: block;
border: none;
width: 100% !important;
}
.tags-wrapper li.tag {
display: flex;
flex-grow: 0;
position: relative;
padding: 10px;
font-size: 14px;
align-items: center;
border-radius: 5px;
list-style: none;
background-image: none;
box-shadow: none;
color: white;
}
.tags-wrapper li a {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
text-decoration: none;
color: rgba(0, 0, 0, 0);
}
.tags-wrapper li a:hover {
background-color: rgba(0, 0, 0, 0.4);
border-radius: 5px;
color: rgba(0, 0, 0);
background-image: url("http://svgshare.com/i/3yv.svg");
background-size: contain;
background-repeat: no-repeat;
background-position: center;
}
.tags-wrapper input {
display: none;
}
#s_item {
display: none
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.staticaly.com/gh/moofawsaw/donorport/master/auto-fill.min.js"></script>
<a id="btn_studio" href="#" class="btn btn--new ripple w-button">Create</a>
<div>keywords are: blue, red, green</div>
<div id="s_list">
<div id="s_item" data-item="studio" data-mode="none" class="post__item studio__item">
<div data-item="studio" class="post__itemwrap post__itemwrap--studio">
<div class="search search--proj w-embed"><label class="search__label--proj" data-color="">
<input type="text" class="input--proj" autocomplete="off" placeholder="">
</label></div>
<div class="w-dyn-list">
<div class="w-dyn-items">
<div class="w-dyn-item">
<div class="w-embed">
<div class="studio__project" data-proj="Blue" data-color="blue"></div>
</div>
</div>
<div class="w-dyn-item">
<div class="w-embed">
<div class="studio__project" data-proj="Green" data-color="green"></div>
</div>
</div>
<div class="w-dyn-item">
<div class="w-embed">
<div class="studio__project" data-proj="Red" data-color="red"></div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
Im creating a floating label , i manage to make a floating label on textbox but
in my dropdown it doesn't work. hope you can help me.
/** GLOBAL OBJECT **/
var $ = {
addClass: function(elem, name) {
var classes = elem.className.split(' '),
cIndex = classes.indexOf(name);
if (cIndex === -1) {
classes.push(name);
}
elem.className = classes.join(' ');
return this;
}, // END addClass
removeClass: function(elem, name) {
var classes = elem.className.split(' '),
cIndex = undefined;
function recursive() {
// use a recursive function to remove all instances
// of the class name
cIndex = classes.indexOf(name);
if (cIndex >= 0) {
classes.splice(cIndex, 1);
recursive();
}
}
recursive();
elem.className = classes.join(' ');
return this;
}, // END removeClass
hasClass: function(elem, name) {
var classes = elem.className.split(' '),
cIndex = classes.indexOf(name);
if (cIndex >= 0) {
return true;
} else {
return false;
}
}, // END hasClass
selectCreate: function(select, label) {
var _this = this;
id = '_' + select.id,
input = document.createElement('input'),
div = document.createElement('div'),
ul = document.createElement('ul'),
val = {
value: select.value,
text: select.options[select.selectedIndex].text
};
select.style.display = 'none';
ul.id = 'ul' + id;
ul.className = 'ddown-list';
ul.setAttribute('aria-live', 'polite');
input.setAttribute('type', 'text');
input.setAttribute('aria-autocomplete', 'list');
input.setAttribute('aria-haspopup', 'true');
input.setAttribute('aria-owns', ul.id);
input.className = 'dynamic-dropdown';
input.id = id;
if (select.getAttribute('data-required') === 'true') {
input.setAttribute('required', 'true');
}
label.setAttribute('for', id);
div.className = 'selectRegion';
div.appendChild(label);
div.appendChild(input);
div.appendChild(ul);
select.parentNode.insertBefore(div, select);
input.value = val.text;
if (input.value !== '') {
this.addClass(label, 'active');
} else {
this.addClass(label, 'inactive');
}
input.addEventListener('focus', function() {
_this.addClass(label, 'active')
.addClass(label, 'transition')
.removeClass(label, 'inactive');
if (this.setSelectionRange) {
this.setSelectionRange(0, this.value.length);
}
populateList(this, select, document.getElementById('ul' + this.id), -1, true);
}); // END focus
input.addEventListener('blur', function() {
var input = this;
setTimeout(function() {
if (input.value === '') {
_this.addClass(label, 'inactive')
.addClass(label, 'transition')
.removeClass(label, 'active');
} else {
var list = getList(input.value, select, false);
select.value = list.value[0];
input.value = list.text[0];
}
document.getElementById('ul' + input.id).innerHTML = '';
}, 250);
}); // END blur
input.addEventListener('keyup', function(e) {
var list = document.getElementById('ul' + this.id).getElementsByTagName('li'),
index = -1,
kC = e.keyCode;
for (var i = 0, x = list.length; i < x; i++) {
if (_this.hasClass(list[i], 'active')) {
index = i;
break;
}
}
if (kC !== 9 && kC !== 16) { // SHIFT && TAB
if (kC === 13) { // ENTER
var list = getList(this.value, select, false);
select.value = list.value[index];
this.value = list.text[index];
document.getElementById('ul' + this.id).innerHTML = '';
} else {
switch (kC) {
case 38: // ARROW UP
index--;
if (index < 0) {
index = 0;
}
break;
case 40: // ARROW DOWN
index++;
if (index >= list.length) {
index = list.length - 1;
}
break;
default:
index = -1;
break;
}
populateList(this, select, document.getElementById('ul' + this.id), index, false);
}
}
}); // END keyup
function populateList(input, select, target, index, focus) {
var list = getList(input.value, select, focus),
counter = 0,
output;
if (focus) {
index = select.selectedIndex - 1;
}
target.innerHTML = '';
for (var i = 0, x = list.value.length; i < x; i++) {
output = document.createElement('li');
if (counter === index) {
output.className = 'active';
}
output.appendChild(document.createTextNode(list.text[i]));
output.addEventListener('click', function() {
console.log('test');
input.value = this.innerHTML;
});
target.appendChild(output);
counter++;
}
if (index >= 0) {
var lis = target.getElementsByTagName('li'),
sTop = 0;
for (var i = 0, x = lis.length; i < x; i++) {
if (i >= index) {
break;
}
sTop += lis[i].clientHeight;
}
target.scrollTop = sTop;
}
} // END populateList
function getList(val, list, focus) {
var value = [],
text = [],
vLength = val.length;
if (focus) {
vLength = 0;
val = '';
}
for (var i = 0, x = list.length; i < x; i++) {
if (list[i].text !== '' &&
(list[i].text.toUpperCase().substring(0, vLength) === val.toUpperCase() ||
list[i].value.toUpperCase().substring(0, vLength) === val.toUpperCase())) {
value.push(list[i].value);
text.push(list[i].text);
}
}
return {
value: value,
text: text
};
} // END function getList
}, // END selectCreate()
}; // END $
window.onload = function() {
var labels = document.getElementsByTagName('label'),
id = '',
label = undefined,
input = undefined,
type = undefined;
for (var i = 0, x = labels.length; i < x; i++) {
label = labels[i];
id = label.getAttribute('for') || '';
input = document.getElementById(id);
if (input) {
type = input.getAttribute('type') || input.tagName;
type = type.toLowerCase();
if (input && (type === 'select')) {
$.selectCreate(input, label);
} // END if( input && select )
}
} // END for( labels )
}();
var demo = function() {
setTimeout(function() {
document.getElementById('_s').focus();
setTimeout(function() {
document.getElementById('_s').blur();
}, 750);
}, 500);
}();
body {
background-color: #F7F7F7;
font-family: Arial;
padding-top: 10%;
}
input,
label,
select {
width: 280px;
padding: 10px;
font-size: 16px;
}
input {
border: solid 1px #CCCCCC;
border: none;
overflow: visible;
outline: none;
background-color: transparent;
border-bottom: solid 1px #999;
}
label {
position: absolute;
}
label.active {
color: #3784BB;
margin-top: -20px;
font-size: 12px;
}
label.inactive {
color: #999999;
}
li.active {
background-color: rgba( 255, 0, 0, 0.1);
}
.transition {
transition: all linear 0.1s;
}
.input {
width: 300px;
margin: auto;
}
.input:first-child {
margin-bottom: 5%
}
.selectRegion {
width: 100%;
}
.selectRegion ul {
margin: 0;
padding: 0;
position: absolute;
width: 300px;
max-height: 200px;
overflow: auto;
box-shadow: 0 2px 3px rgba( 0, 0, 0, 0.1);
background-color: #FFFFFF;
z-index: 2;
}
.selectRegion ul li {
padding: 10px;
}
.selectRegion ul li:hover {
cursor: pointer;
}
.inputbox {
position: relative;
background: none;
margin-right: 50px;
}
.inputbox input {
width: 120%;
padding: 10px 0;
font-size: 19px;
color: #21a1e;
margin-bottom: 50px;
overflow: visible;
outline: none;
background-color: transparent;
border: none;
border-bottom: solid 1px #999;
margin-left: -10px;
margin-top: -15px;
}
.inputbox label {
display: block;
position: absolute;
top: 0;
left: 0;
padding: 10px 0;
font-size: 16px;
color: #999;
pointer-events: none;
transition: top 0.7s ease, opacity 0.7s ease;
border-radius: .25rem;
margin-left: -10px;
margin-top: -10px;
}
.inputbox input:focus+label,
.inputbox input:valid+label {
top: -18px;
left: 0;
color: #4285f4;
font-size: 12px;
cursor: pointer;
}
<html>
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js"></script>
</head>
<body>
<div class="col-sm-5">
<button type="button" class="button2 " data-toggle="modal" data-target="#exampleModal1">Login</button>
</div>
<div class="modal fade" id="exampleModal1" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog modal-lg " role="document">
<div class="modal-content">
<div class="modal-header ">
<h5 class="modal-title" id="exampleModalLabel" style=" color: #404E67;">Form</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<form>
<div class="form-row ">
<div class="inputbox">
<input type="text" required>
<label>First Name </label>
</div>
<div class="inputbox">
<input type="text" required>
<label>Last Name</label>
</div>
</div>
<div class="form-row">
<div class="input">
<label for="s">Sample 1:</label>
<select id="s">
<option value=""></option>
<option value="1">Assignment</option>
<option value="2">Reading</option>
</select>
</div>
</div>
<div class="clear"></div>
<div class="input">
<label for="state">Sample 2</label>
<select id="state">
<option value=""></option>
<option value="AL">Alabama</option>
<option value="AK">Alaska</option>
</select>
</div>
</form>
</div>
</div>
</body>
</html>
here is my current output:
As you can see on my output the two dropdown is not working any idea how ca i make it a floating label like at my textbox?
I don't know how to describe this without making it more complicated.
So look at the result of the code and click on the first link with "Show", then the second one and third one.
When the second link is clicked, first one closes but text remains "Hide" and i want it to change to "Show".
So, when clicking a link, detect if any other link has text "Hide" and change it to "Show".
And please no jQuery...
document.getElementsByClassName("show")[0].onclick = function() {
var x = document.getElementsByClassName("hide")[0];
var y = document.getElementsByClassName("show")[0];
if (x.classList.contains("visible")) {
x.classList.remove("visible");
y.textContent = "Show";
} else {
closeOther();
x.classList.add("visible");
y.textContent = "Hide";
}
};
document.getElementsByClassName("show")[1].onclick = function() {
var x = document.getElementsByClassName("hide")[1];
var y = document.getElementsByClassName("show")[1];
if (x.classList.contains("visible")) {
x.classList.remove("visible");
y.textContent = "Show";
} else {
closeOther();
x.classList.add("visible");
y.textContent = "Hide";
}
};
document.getElementsByClassName("show")[2].onclick = function() {
var x = document.getElementsByClassName("hide")[2];
var y = document.getElementsByClassName("show")[2];
if (x.classList.contains("visible")) {
x.classList.remove("visible");
y.textContent = "Show";
} else {
closeOther();
x.classList.add("visible");
y.textContent = "Hide";
}
};
function closeOther() {
var visible = document.querySelectorAll(".visible"),
i, l = visible.length;
for (i = 0; i < l; ++i) {
visible[i].classList.remove("visible");
}
}
.style {
background-color: yellow;
width: 200px;
height: 200px;
display: inline-block;
}
.hide {
background-color: red;
width: 50px;
height: 50px;
display: none;
position: relative;
top: 50px;
left: 50px;
}
.hide.visible {
display: block;
}
<div class="style">
Show
<div class="hide">
</div>
</div>
<div class="style">
Show
<div class="hide">
</div>
</div>
<div class="style">
Show
<div class="hide">
</div>
</div>
I tried to write a solution which didn't use any javascript at all and worked using CSS alone. I couldn't get it to work though - CSS can identify focus but it can't identify blur (ie. when focus has just been removed).
So here is a solution which uses javascript and the classList API, instead:
var divs = document.getElementsByTagName('div');
function toggleFocus() {
for (var i = 0; i < divs.length; i++) {
if (divs[i] === this) continue;
divs[i].classList.add('show');
divs[i].classList.remove('hide');
}
this.classList.toggle('show');
this.classList.toggle('hide');
}
for (let i = 0; i < divs.length; i++) {
divs[i].addEventListener('click', toggleFocus, false);
}
div {
display: inline-block;
position: relative;
width: 140px;
height: 140px;
background-color: rgb(255,255,0);
}
.show::before {
content: 'show';
}
.hide::before {
content: 'hide';
}
div::before {
color: rgb(0,0,255);
text-decoration: underline;
cursor: pointer;
}
.hide::after {
content: '';
position: absolute;
top: 40px;
left: 40px;
width: 50px;
height: 50px;
background-color: rgb(255,0,0);
}
<div class="show"></div>
<div class="show"></div>
<div class="show"></div>
Like this?
Just added following to closeOther():
visible = document.querySelectorAll(".show"),
i, l = visible.length;
for (i = 0; i < l; ++i) {
visible[i].textContent="Show";
}
I've got a bunch of horizontal boxes containing text. The boxes are all in a horizontally scrolling container:
// generate some random data
var model = {
leftEdge: ko.observable(0)
};
model.rows = populateArray(10 + randInt(20), randRow);
ko.applyBindings(model);
$(function() {
$('.slide').on('scroll', function() {
model.leftEdge(this.scrollLeft);
})
})
function randRow() {
var events = populateArray(50 + randInt(100), randEvent);
var left = randInt(1000);
events.forEach(function(event) {
event.left = left;
left += 10 + event.width + randInt(1000);
});
return {
events: events
}
}
function randEvent() {
var word = randWord()
var width = 50 + Math.max(8 * word.length, randInt(200));
var event = {
left: 0,
width: width,
label: word
};
event.offset = ko.computed(function() {
// reposition the text to stay
// * within its container
// * fully on-screen (if possible)
var leftEdge = model.leftEdge();
return Math.max(0, Math.min(
leftEdge - event.left,
event.width - 8 * event.label.length
));
});
return event;
}
function randWord() {
var n = 2 + randInt(5);
var ret = "";
while (n-- > 0) {
ret += randElt("rmhntsk");
ret += randElt("aeiou");
}
return ret;
}
function randElt(arr) {
return arr[randInt(arr.length)];
}
function populateArray(n, populate) {
var arr = new Array(n);
for (var i = 0; i < n; i++) {
arr[i] = populate();
}
return arr;
}
function randInt(n) {
return Math.floor(Math.random() * n);
}
.slide {
max-width: 100%;
overflow: auto;
border: 5px solid black;
}
.row {
position: relative;
height: 25px;
}
.event {
position: absolute;
top: 2.5px;
border: 1px solid black;
padding: 2px;
background: #cdffff;
font-size: 14px;
font-family: monospace;
}
.event > span {
position: relative;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<div class="slide" data-bind="foreach: rows">
<div class="row" data-bind="foreach: events">
<div class="event" data-bind="style: { left: left+'px', width: width+'px' }"><span data-bind="text:label, style: { left: offset() + 'px' }"></div>
</div>
</div>
What I'd like to do is as the user scrolls from left-to-right, reposition the text within each box that partially overlaps the left border of the visible window to keep the text as visible as possible.
Currently I'm doing this by manually repositioning each item of text.
Is there a cleaner way to do this using CSS?
A friend helped me come up with this solution.
In English, the idea is to add an overlay to each row that is positioned relatively to the frame of the scrolling box, rather than the contents.
Then we can place a label for any box that overlaps the left edge in this overlay and it will appear to smoothly move as the box underneath it scrolls.
// generate some random data
var model = {
leftEdge: ko.observable(0),
};
model.rows = populateArray(10 + randInt(20), randRow);
model.width = Math.max.apply(Math, $.map(model.rows, function(row) {
return row.width
}));
ko.applyBindings(model);
$(function() {
$('.slide').on('scroll', function() {
model.leftEdge(this.scrollLeft);
})
})
function randRow() {
var events = populateArray(50 + randInt(100), randEvent);
var left = randInt(1000);
events.forEach(function(event) {
event.left = left;
left += 10 + event.width + randInt(1000);
});
return {
events: events,
width: left
}
}
function randEvent() {
var word = randWord()
var width = 50 + Math.max(8 * word.length, randInt(200));
var event = {
width: width,
label: word,
};
event.tense = ko.computed(function() {
// reposition the text to stay#
// * within its container
// * fully on-screen (if possible)
var leftEdge = model.leftEdge();
return ['future', 'present', 'past'][
(leftEdge >= event.left) +
(leftEdge > event.left + event.width - 8 * event.label.length)
];
});
return event;
}
function randWord() {
var n = 2 + randInt(5);
var ret = "";
while (n-- > 0) {
ret += randElt("rmhntsk");
ret += randElt("aeiou");
}
return ret;
}
function randElt(arr) {
return arr[randInt(arr.length)];
}
function populateArray(n, populate) {
var arr = new Array(n);
for (var i = 0; i < n; i++) {
arr[i] = populate();
}
return arr;
}
function randInt(n) {
return Math.floor(Math.random() * n);
}
.wrapper {
position: relative;
border: 5px solid black;
font-size: 14px;
font-family: monospace;
}
.slide {
max-width: 100%;
overflow: auto;
}
.slide > * {
height: 25px;
}
.overlay {
position: absolute;
width: 100%;
left: 0;
}
.overlay .past {
display: none
}
.overlay .present {
position: absolute;
z-index: 1;
top: 5.5px;
left 0;
}
.overlay .future {
display: none
}
.row {
position: relative;
}
.event {
position: absolute;
top: 2.5px;
border: 1px solid black;
padding: 2px;
background: #cdffff;
height: 14px;
}
.event .past {
float: right;
}
.event .present {
display: none;
}
.event .future {
float: left;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<div class="wrapper">
<div class="slide" data-bind="foreach: rows, style: { width: width + 'px' }">
<div class="overlay" data-bind="foreach: events">
<span data-bind="text:label, css: tense"></span>
</div>
<div class="row" data-bind="foreach: events">
<div class="event" data-bind="style: { left: left+'px', width: width+'px' }"><span data-bind="text:label, css: tense"></div>
</div>
</div></div>
This doesn't result in less javascript, but it does result in more efficient javascript, as class changes happen much less often than offset changes, so fewer updates to DOM elements are required.
You can avoid processing every "event" (in the above example) by doing some pre-partitioning of the horizontal space, and only updating events in the relevant partition.
Some of us might not want to use ready plugins because of their high sizes and possibilty of creating conflicts with current javascript.
I was using light slider plugins before but when customer gives modular revise, it became really hard to manipulate. Then I aim to build mine for customising it easily. I believe sliders shouldn't be that complex to build from beginning.
What is a simple and clean way to build jQuery image slider?
Before inspecting examples, you should know two jQuery functions which i used most.
index() returns value is an integer indicating the position of the first element within the jQuery object relative to its sibling elements.
eq() selects of an element based on its position (index value).
Basicly i take selected trigger element's index value and match this value on images with eq method.
- FadeIn / FadeOut effect.
- Sliding effect.
- alternate Mousewheel response.
html sample:
<ul class="images">
<li>
<img src="images/1.jpg" alt="1" />
</li>
<li>
<img src="images/2.jpg" alt="2" />
</li>
...
</ul>
<ul class="triggers">
<li>1</li>
<li>2</li>
...
</ul>
<span class="control prev">Prev</span>
<span class="control next">Next</span>
OPACITY EFFECT: jsFiddle.
css trick: overlapping images with position:absolute
ul.images { position:relative; }
ul.images li { position:absolute; }
jQuery:
var target;
var triggers = $('ul.triggers li');
var images = $('ul.images li');
var lastElem = triggers.length-1;
triggers.first().addClass('active');
images.hide().first().show();
function sliderResponse(target) {
images.fadeOut(300).eq(target).fadeIn(300);
triggers.removeClass('active').eq(target).addClass('active');
}
SLIDING EFFECT: jsFiddle.
css trick: with double wrapper and use child as mask
.mask { float:left; margin:40px; width:270px; height:266px; overflow:hidden; }
ul.images { position:relative; top:0px;left:0px; }
/* this width must be total of the images, it comes from jquery */
ul.images li { float:left; }
jQuery:
var target;
var triggers = $('ul.triggers li');
var images = $('ul.images li');
var lastElem = triggers.length-1;
var mask = $('.mask ul.images');
var imgWidth = images.width();
triggers.first().addClass('active');
mask.css('width', imgWidth*(lastElem+1) +'px');
function sliderResponse(target) {
mask.stop(true,false).animate({'left':'-'+ imgWidth*target +'px'},300);
triggers.removeClass('active').eq(target).addClass('active');
}
Common jQuery response for both slider:
( triggers + next/prev click and timing )
triggers.click(function() {
if ( !$(this).hasClass('active') ) {
target = $(this).index();
sliderResponse(target);
resetTiming();
}
});
$('.next').click(function() {
target = $('ul.triggers li.active').index();
target === lastElem ? target = 0 : target = target+1;
sliderResponse(target);
resetTiming();
});
$('.prev').click(function() {
target = $('ul.triggers li.active').index();
lastElem = triggers.length-1;
target === 0 ? target = lastElem : target = target-1;
sliderResponse(target);
resetTiming();
});
function sliderTiming() {
target = $('ul.triggers li.active').index();
target === lastElem ? target = 0 : target = target+1;
sliderResponse(target);
}
var timingRun = setInterval(function() { sliderTiming(); },5000);
function resetTiming() {
clearInterval(timingRun);
timingRun = setInterval(function() { sliderTiming(); },5000);
}
Here is a simple and easy to understand code for Creating image slideshow using JavaScript without using Jquery.
<script language="JavaScript">
var i = 0; var path = new Array();
// LIST OF IMAGES
path[0] = "image_1.gif";
path[1] = "image_2.gif";
path[2] = "image_3.gif";
function swapImage() { document.slide.src = path[i];
if(i < path.length - 1) i++;
else i = 0; setTimeout("swapImage()",3000);
} window.onload=swapImage;
</script>
<img height="200" name="slide" src="image_1.gif" width="400" />
I have recently created a solution with a gallery of images and a slider that apears when an image is clicked.
Take a look at the code here: GitHub Code
And a live example here: Code Example
var CreateGallery = function(parameters) {
var self = this;
this.galleryImages = [];
this.galleryImagesSrcs = [];
this.galleryImagesNum = 0;
this.counter;
this.galleryTitle = parameters.galleryTitle != undefined ? parameters.galleryTitle : 'Gallery image';
this.maxMobileWidth = parameters.maxMobileWidth != undefined ? parameters.maxMobileWidth : 768;
this.numMobileImg = parameters.numMobileImg != undefined ? parameters.numMobileImg : 2;
this.maxTabletWidth = parameters.maxTabletWidth != undefined ? parameters.maxTabletWidth : 1024;
this.numTabletImg = parameters.numTabletImg != undefined ? parameters.numTabletImg : 3;
this.addModalGallery = function(gallerySelf = self){
var $div = $(document.createElement('div')).attr({
'id': 'modal-gallery'
}).append($(document.createElement('div')).attr({
'class': 'header'
}).append($(document.createElement('button')).attr({
'class': 'close-button',
'type': 'button'
}).html('×')
).append($(document.createElement('h2')).text(gallerySelf.galleryTitle))
).append($(document.createElement('div')).attr({
'class': 'text-center'
}).append($(document.createElement('img')).attr({
'id': 'gallery-img'
})
).append($(document.createElement('button')).attr({
'class': 'prev-button',
'type': 'button'
}).html('◄')
).append($(document.createElement('button')).attr({
'class': 'next-button',
'type': 'button'
}).html('►')
)
);
parameters.element.after($div);
};
$(document).on('click', 'button.prev-button', {self: self}, function() {
var $currImg = self.counter >= 1 ? self.galleryImages[--self.counter] : self.galleryImages[self.counter];
var $currHash = self.galleryImagesSrcs[self.counter];
var $src = $currImg.src;
window.location.hash = $currHash;
$('img#gallery-img').attr('src', $src);
$('div#modal-gallery h2').text(self.galleryTitle + ' ' + (self.counter + 1));
});
$(document).on('click', 'button.next-button', {self: self}, function() {
var $currImg = self.counter < (self.galleryImagesNum - 1) ? self.galleryImages[++self.counter] : self.galleryImages[self.counter];
var $currHash = self.galleryImagesSrcs[self.counter];
var $src = $currImg.src;
window.location.hash = $currHash;
$('img#gallery-img').attr('src', $src);
$('div#modal-gallery h2').text(self.galleryTitle + ' ' + (self.counter + 1));
});
$(document).on('click', 'div#modal-gallery button.close-button', function() {
$('#modal-gallery').css('position', 'relative');
$('#modal-gallery').hide();
$('body').css('overflow', 'visible');
});
parameters.element.find('a').on('click', {self: self}, function(event) {
event.preventDefault();
$('#modal-gallery').css('position', 'fixed');
$('#modal-gallery').show();
$('body').css('overflow', 'hidden');
var $currHash = this.hash.substr(1);
self.counter = self.galleryImagesSrcs.indexOf($currHash);
var $src = $currHash;
window.location.hash = $currHash;
$('img#gallery-img').attr('src', $src);
$('div#modal-gallery h2').text(self.galleryTitle + ' ' + (self.counter + 1));
});
this.sizeGallery = function(gallerySelf = self) {
var $modalGallery = $(document).find("div#modal-gallery");
if($modalGallery.length <= 0) {
this.addModalGallery();
}
var $windowWidth = $(window).width();
var $parentWidth = parameters.element.width();
var $thumbnailHref = parameters.element.find('img:first').attr('src');
if($windowWidth < gallerySelf.maxMobileWidth) {
var percentMobile = Math.floor(100 / gallerySelf.numMobileImg);
var emMobile = 0;
var pxMobile = 2;
// var emMobile = gallerySelf.numMobileImg * 0.4;
// var pxMobile = gallerySelf.numMobileImg * 2;
parameters.element.find('img').css('width', 'calc('+percentMobile+'% - '+emMobile+'em - '+pxMobile+'px)');
} else if($windowWidth < gallerySelf.maxTabletWidth) {
var percentTablet = Math.floor(100 / gallerySelf.numTabletImg);
var emTablet = 0;
var pxTablet = 2;
// var emTablet = gallerySelf.numMobileImg * 0.4;
// var pxTablet = gallerySelf.numMobileImg * 2;
parameters.element.find('img').css('width', 'calc('+percentTablet+'% - '+emTablet+'em - '+pxTablet+'px)');
} else {
var $thumbImg = new Image();
$thumbImg.src = $thumbnailHref;
$thumbImg.onload = function() {
var $thumbnailWidth = this.width;
if($parentWidth > 0 && $thumbnailWidth > 0) {
parameters.element.find('img').css('width', (Math.ceil($thumbnailWidth * 100 / $parentWidth))+'%');
}
};
}
};
this.startGallery = function(gallerySelf = self) {
parameters.element.find('a').each(function(index, el) {
var $currHash = el.hash.substr(1);
var $img = new Image();
$img.src = $currHash;
gallerySelf.galleryImages.push($img);
gallerySelf.galleryImagesSrcs.push($currHash);
});
this.galleryImagesNum = this.galleryImages.length;
};
this.sizeGallery();
this.startGallery();
};
var myGallery;
$(window).on('load', function() {
myGallery = new CreateGallery({
element: $('#div-gallery'),
maxMobileWidth: 768,
numMobileImg: 2,
maxTabletWidth: 1024,
numTabletImg: 3
});
});
$(window).on('resize', function() {
myGallery.sizeGallery();
});
#div-gallery {
text-align: center;
}
#div-gallery img {
margin-right: auto;
margin-left: auto;
}
div#modal-gallery {
top: 0;
left: 0;
width: 100%;
max-width: none;
height: 100vh;
min-height: 100vh;
margin-left: 0;
border: 0;
border-radius: 0;
z-index: 1006;
-webkit-backface-visibility: hidden;
backface-visibility: hidden;
display: none;
background-color: #fefefe;
position: relative;
margin-right: auto;
overflow-y: auto;
padding: 0;
}
div#modal-gallery div.header {
position: relative;
}
div#modal-gallery div.header h2 {
margin-left: 1rem;
}
div#modal-gallery div.header button.close-button {
position: absolute;
top: calc(50% - 1em);
right: 1rem;
}
div#modal-gallery img {
display: block;
max-width: 98%;
max-height: calc(100vh - 5em);
margin-right: auto;
margin-left: auto;
}
div#modal-gallery div.text-center {
position: relative;
}
button.close-button {
display: inline-block;
padding: 6px 12px;
margin-bottom: 0;
font-size: 20px;
font-weight: 400;
line-height: 1.42857143;
text-align: center;
white-space: nowrap;
vertical-align: middle;
-ms-touch-action: manipulation;
touch-action: manipulation;
cursor: pointer;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
background-image: none;
border: 1px solid transparent;
border-radius: 4px;
color: #333;
background-color: #fff;
border-color: #ccc;
}
button.close-button:hover, button.close-button:focus {
background-color: #ddd;
}
button.next-button:hover, button.prev-button:hover, button.next-button:focus, button.prev-button:focus {
color: #fff;
text-decoration: none;
filter: alpha(opacity=90);
outline: 0;
opacity: .9;
}
button.next-button, button.prev-button {
position: absolute;
top: 0;
bottom: 0;
left: 0;
width: 15%;
font-size: 20px;
color: #fff;
text-align: center;
text-shadow: 0 1px 2px rgba(0,0,0,.6);
background-color: rgba(0,0,0,0);
filter: alpha(opacity=50);
opacity: .5;
border: none;
}
button.next-button {
right: 0;
left: auto;
background-image: -webkit-linear-gradient(left,rgba(0,0,0,.0001) 0,rgba(0,0,0,.5) 100%);
background-image: -o-linear-gradient(left,rgba(0,0,0,.0001) 0,rgba(0,0,0,.5) 100%);
background-image: -webkit-gradient(linear,left top,right top,from(rgba(0,0,0,.0001)),to(rgba(0,0,0,.5)));
background-image: linear-gradient(to right,rgba(0,0,0,.0001) 0,rgba(0,0,0,.5) 100%);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#00000000', endColorstr='#80000000', GradientType=1);
background-repeat: repeat-x;
}
button.prev-button {
background-image: -webkit-linear-gradient(left,rgba(0,0,0,.5) 0,rgba(0,0,0,.0001) 100%);
background-image: -o-linear-gradient(left,rgba(0,0,0,.5) 0,rgba(0,0,0,.0001) 100%);
background-image: -webkit-gradient(linear,left top,right top,from(rgba(0,0,0,.5)),to(rgba(0,0,0,.0001)));
background-image: linear-gradient(to right,rgba(0,0,0,.5) 0,rgba(0,0,0,.0001) 100%);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#80000000', endColorstr='#00000000', GradientType=1);
background-repeat: repeat-x;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="div-gallery">
<img src="http://placehold.it/300x300/ff0000/000000?text=Gallery+image+1" alt="">
<img src="http://placehold.it/300x300/ff4000/000000?text=Gallery+image+2" alt="">
<img src="http://placehold.it/300x300/ff8000/000000?text=Gallery+image+3" alt="">
<img src="http://placehold.it/300x300/ffbf00/000000?text=Gallery+image+4" alt="">
<img src="http://placehold.it/300x300/ffff00/000000?text=Gallery+image+5" alt="">
<img src="http://placehold.it/300x300/bfff00/000000?text=Gallery+image+6" alt="">
<img src="http://placehold.it/300x300/80ff00/000000?text=Gallery+image+7" alt="">
<img src="http://placehold.it/300x300/40ff00/000000?text=Gallery+image+8" alt="">
<img src="http://placehold.it/300x300/00ff00/000000?text=Gallery+image+9" alt="">
<img src="http://placehold.it/300x300/00ff40/000000?text=Gallery+image+10" alt="">
<img src="http://placehold.it/300x300/00ff80/000000?text=Gallery+image+11" alt="">
<img src="http://placehold.it/300x300/00ffbf/000000?text=Gallery+image+12" alt="">
<img src="http://placehold.it/300x300/00ffff/000000?text=Gallery+image+13" alt="">
<img src="http://placehold.it/300x300/00bfff/000000?text=Gallery+image+14" alt="">
<img src="http://placehold.it/300x300/0080ff/000000?text=Gallery+image+15" alt="">
<img src="http://placehold.it/300x300/0040ff/000000?text=Gallery+image+16" alt="">
</div>
Checkout this whole bunch of code to build simple jquery image slider. Copy and save this file to local machine and test it. You can modify it according to your requirement.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script>
var current_img = 1;
var i;
$(document).ready(function(){
var imgs = $("#image").find("img");
function show_img(){
for (i = 1; i < imgs.length+1; i++) {
if(i == current_img){
$(imgs[i-1]).show();
}else{
$(imgs[i-1]).hide()
}
}
}
$("#prev").click(function(){
if(current_img == 1){
current_img = imgs.length;
}else{
current_img = current_img - 1
}
show_img();
});
$("#next").click(function(){
if(current_img == imgs.length){
current_img = 1;
}else{
current_img = current_img + 1
}
show_img();
});
});
</script>
</head>
<body>
<div style="margin-top: 100px;"></div>
<div class="container">
<div class="col-sm-3">
<button type="button" id="prev" class="btn">Previous</button>
</div>
<div class="col-sm-6">
<div id="image">
<img src="https://www.w3schools.com/html/pulpitrock.jpg" alt="image1">
<img src="https://www.w3schools.com/cSS/img_forest.jpg" alt="image2" hidden="true" style="max-width: 500px;">
<img src="https://www.w3schools.com/html/img_chania.jpg" alt="image3" hidden="true">
</div>
</div>
<div class="col-sm-3">
<button type="button" id="next" class="btn">Next</button>
</div>
</div>
</body>
</html>
I have written a tutorial on creating a slideshow, The tutorial page
In case the link becomes invalid I have included the code in my answer below.
the html:
<div id="slideShow">
<div id="slideShowWindow">
<div class="slide">
<img src="”img1.png”/">
<div class="slideText">
<h2>The Slide Title</h2>
<p>This is the slide text</p>
</div> <!-- </slideText> -->
</div> <!-- </slide> repeat as many times as needed -->
</div> <!-- </slideShowWindow> -->
</div> <!-- </slideshow> -->
css:
img {
display: block;
width: 100%;
height: auto;
}
p{
background:none;
color:#ffffff;
}
#slideShow #slideShowWindow {
width: 650px;
height: 450px;
margin: 0;
padding: 0;
position: relative;
overflow:hidden;
margin-left: auto;
margin-right:auto;
}
#slideShow #slideShowWindow .slide {
margin: 0;
padding: 0;
width: 650px;
height: 450px;
float: left;
position: relative;
margin-left:auto;
margin-right: auto;
}
#slideshow #slideshowWindow .slide, .slideText {
position:absolute;
bottom:18px;
left:0;
width:100%;
height:auto;
margin:0;
padding:0;
color:#ffffff;
font-family:Myriad Pro, Arial, Helvetica, sans-serif;
}
.slideText {
background: rgba(128, 128, 128, 0.49);
}
#slideshow #slideshowWindow .slide .slideText h2,
#slideshow #slideshowWindow .slide .slideText p {
margin:10px;
padding:15px;
}
.slideNav {
display: block;
text-indent: -10000px;
position: absolute;
cursor: pointer;
}
#leftNav {
left: 0;
bottom: 0;
width: 48px;
height: 48px;
background-image: url("../Images/plus_add_minus.png");
background-repeat: no-repeat;
z-index: 10;
}
#rightNav {
right: 0;
bottom: 0;
width: 48px;
height: 48px;
background-image: url("../Images/plus_add_green.png");
background-repeat: no-repeat;
z-index: 10; }
jQuery:
$(document).ready(function () {
var currentPosition = 0;
var slideWidth = 650;
var slides = $('.slide');
var numberOfSlides = slides.length;
var slideShowInterval;
var speed = 3000;
//Assign a timer, so it will run periodically
slideShowInterval = setInterval(changePosition, speed);
slides.wrapAll('<div id="slidesHolder"></div>');
slides.css({ 'float': 'left' });
//set #slidesHolder width equal to the total width of all the slides
$('#slidesHolder').css('width', slideWidth * numberOfSlides);
$('#slideShowWindow')
.prepend('<span class="slideNav" id="leftNav">Move Left</span>')
.append('<span class="slideNav" id="rightNav">Move Right</span>');
manageNav(currentPosition);
//tell the buttons what to do when clicked
$('.slideNav').bind('click', function () {
//determine new position
currentPosition = ($(this).attr('id') === 'rightNav')
? currentPosition + 1 : currentPosition - 1;
//hide/show controls
manageNav(currentPosition);
clearInterval(slideShowInterval);
slideShowInterval = setInterval(changePosition, speed);
moveSlide();
});
function manageNav(position) {
//hide left arrow if position is first slide
if (position === 0) {
$('#leftNav').hide();
}
else {
$('#leftNav').show();
}
//hide right arrow is slide position is last slide
if (position === numberOfSlides - 1) {
$('#rightNav').hide();
}
else {
$('#rightNav').show();
}
}
//changePosition: this is called when the slide is moved by the timer and NOT when the next or previous buttons are clicked
function changePosition() {
if (currentPosition === numberOfSlides - 1) {
currentPosition = 0;
manageNav(currentPosition);
} else {
currentPosition++;
manageNav(currentPosition);
}
moveSlide();
}
//moveSlide: this function moves the slide
function moveSlide() {
$('#slidesHolder').animate({ 'marginLeft': slideWidth * (-currentPosition) });
}
});