I have the following img tag,
<img id="image1" src="URL" alt="image1" name="image1" width="137" height="119" border="0" style="position: relative; left: -355px; top: 62px;" >
I would like to somehow, onclick, store the following items into seperate variables..
style="position: relative; left: -355px; top: 62px;"
var left = -355px
var top = 62px
Is that possible? Thank you!
Of course this is possible, have you tried something like this:
$('#image1').on('click', function () {
var style = 'style="' + $(this).attr('style') + '"';
var left = $(this).css('left');
var top = $(this).css('top');
alert(style);
alert(left);
alert(top);
});
Example: http://jsfiddle.net/9ZXHX/
var imageInfo = {style:null, left:null, top:null};
$('#image1').on('click', function() {
var $this = $(this);
imageInfo.style = $this.attr('style');
imageInfo.left = $this.css('left');
imageInfo.top = $this.css('top');
console.log('Image Clicked: ', imageInfo);
});
You could get the image with jquery, and then access its attributes from there.
var img = $("#image1");
var imgStyle = img[0].getAttribute("style");
var imgLeft = img.css("left");
var imgRight = img.css("right");
link to jquery's api for css: http://api.jquery.com/css/
In a function:
function getDetails(imgId)
{
var imgDetails = {};
var img = $("#"+imgId);
imgDetails.imgStyle = img[0].getAttribute("style");
imgDetails.imgLeft = img.css("left");
imgDetails.imgRight = img.css("right");
return imgDetails;
}
Here is a fiddle showing an example of this working, and the requested output in the question: http://jsfiddle.net/j7eYf/1/
I suggest your use jquery, it will make the job a lot easier. Try out this example,
$("#your trigger").live('click',function ()
{
$("#image1").css({
position: "absolute",
top: 62 + "px",
left: -355 + "px"
});
});
Related
I have 30 images that make together a full turn of a 3D model. I want to display the animation in browser. I can not use CSS animation, which otherwise worked good. The problem with JavaScript is flickering when the next image loads. Is there any way to make it smoother?
<div id="image" style="width: 1920px; height: 1080px;">
</div>
<script>
let suffix;
let i = 0;
let image = document.getElementById("image");
function setSuffix(){
suffix = ("0" + (i+1)).slice(-2);
i++;
i = i % 30;
image.style.background = "URL('" + suffix + ".jpg')";
}
setInterval(setSuffix, 1000);
</script>
Perhaps you can use a supplemental image, load it, then bring it to the front using z-index. Something like:
let suffix;
let i = 0;
let image1 = document.getElementById("image1");
let image2 = document.getElementById("image2");
// TIP: Remove these
let url1 = "https://scontent-iad3-1.xx.fbcdn.net/v/t1.0-9/41667401_10155851253461762_5185170392754421760_n.png?_nc_cat=101&oh=beb534388a04dd5ea101bc9560fa5e24&oe=5C1F4FAD";
let url2 = "https://scontent-iad3-1.xx.fbcdn.net/v/t1.0-9/34661720_10155632057856762_4698625317663670272_n.jpg?_nc_cat=106&oh=dd89a8d15e587dba4b7fe8b3ea38143e&oe=5C1E5CC0";
function setSuffix(){
// TIP: Uncomment this
//imageUrl = ("0" + (i+1)).slice(-2) + ".jpg";
if (i % 2 === 0) {
imageUrl = url1; // TIP: Remove this.
image1.style.background = `URL('${imageUrl}')`;
image1.style.zIndex = "1";
image2.style.zIndex = "0";
} else {
imageUrl = url2; // TIP: Remove this.
image2.style.background = `URL('${imageUrl}')`;
image2.style.zIndex = "1";
image1.style.zIndex = "0";
}
i++;
}
setInterval(setSuffix, 1000);
#image1, #image2{
position:absolute;
top: 0px;
left: 0px;
}
<div id="image1" style="width: 1920px; height: 1080px;"></div>
<div id="image2" style="width: 1920px; height: 1080px;"></div>
I know this question is maybe a bit boring. But I'm searching now for serveral hours and find no way to combine the solutions I found on the Internet.
So I hope someone here would like to help me out.
I have a simple Image slider and I need a counter that says maybe "Image 2 of 3".
As I said, there are a lot of solutions on the internet but I'm not able to implement them to my code.
This is the code Im working with:
HTML
<div class="slider">
<img src="http://placehold.it/250x500" class="active"/>
<img src="http://placehold.it/200x500" />
<img src="http://placehold.it/100x500" />
</div>
<!-- ARROW AND COUNTER -->
<div>
<img src="assets/img/arrow-prev.png" class="prev" alt="Prev Arrow"/>
<span id="counter"></span>
<img src="assets/img/arrow-next.png" class="next" alt="Next Arrow"/>
</div>
CSS
.slider{
height: 51vh;
overflow: hidden;
}
.slider img{
display: none;
height: 51vh;
}
.slider img.active{
display: inline-block;
}
.prev, .next{
cursor: pointer;
}
JAVASCRIPT
$(document).ready(function () {
$('.next').on('click', function () {
var currentImg = $('.active');
var nextImg = currentImg.next();
if (nextImg.length) {
currentImg.removeClass('active').css('z-index', -10);
nextImg.addClass('active').css('z-index', 10);
}
});
$('.prev').on('click', function () {
var currentImg = $('.active');
var prevImg = currentImg.prev();
if (prevImg.length) {
currentImg.removeClass('active').css('z-index', -10);
prevImg.addClass('active').css('z-index', 10);
}
});
});
It would be really great if someome can help me!
So basically you should just keep track of all images and the index of the currently displayed image. Something like the code below could do that.
$(document).ready(function () {
// Get images.
var images = $('.slider > img');
// Set starting index.
var index = images.index($('.active'));
$('#counter').text((index + 1) + ' of ' + images.length);
$('.next').on('click', function () {
var currentImg = $('.active');
var nextImg = currentImg.next();
if (nextImg.length) {
currentImg.removeClass('active').css('z-index', -10);
nextImg.addClass('active').css('z-index', 10);
// Find the index of the image.
var index = images.index(nextImg);
$('#counter').text((index + 1) + ' of ' + images.length);
}
});
$('.prev').on('click', function () {
var currentImg = $('.active');
var prevImg = currentImg.prev();
if (prevImg.length) {
currentImg.removeClass('active').css('z-index', -10);
prevImg.addClass('active').css('z-index', 10);
// Find the index of the image.
var index = images.index(prevImg);
$('#counter').text((index + 1) + ' of ' + images.length);
}
});
});
Link to jsfiddle example.
Explanation: I've added a index variable that checks the active class position:
var index = images.index($('.active'));
$('#counter').text("Image " + (index + 1) + ' of ' + images.length);
Working code:
So Have a look at this code because this should work fine!
$(document).ready(function() {
var images = $('.slider > img');
var index = images.index($('.active'));
$('#counter').text("Image " + (index + 1) + ' of ' + images.length);
$('.next').on('click', function() {
var currentImg = $('.active');
var nextImg = currentImg.next();
if (nextImg.length) {
currentImg.removeClass('active').css('z-index', -10);
nextImg.addClass('active').css('z-index', 10);
var index = images.index(nextImg);
$('#counter').text("Image " + (index + 1) + ' of ' + images.length);
}
});
$('.prev').on('click', function() {
var currentImg = $('.active');
var prevImg = currentImg.prev();
if (prevImg.length) {
currentImg.removeClass('active').css('z-index', -10);
prevImg.addClass('active').css('z-index', 10);
var index = images.index(prevImg);
$('#counter').text("Image " + (index + 1) + ' of ' + images.length);
}
});
});
.slider {
height: 51vh;
overflow: hidden;
}
.slider img {
display: none;
height: 51vh;
}
.slider img.active {
display: inline-block;
}
.prev,
.next {
cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="slider">
<img src="https://placehold.it/450x500/red" class="active" />
<img src="https://placehold.it/450x500/r" />
<img src="https://placehold.it/450x500" />
</div>
<!-- ARROW AND COUNTER -->
<div>
<img src="https://placehold.it/50/red" class="prev" alt="Prev Arrow" />
<span id="counter"></span>
<img src="https://placehold.it/50/blue" class="next" alt="Next Arrow" />
</div>
I hope this is the solution you have expected. For any further questions to my answer - let me know :)
Without jQuery, just plain javascript.
With css opacity transition.
https://jsfiddle.net/uatthqjp/3/
const $images = document.querySelectorAll('img');
// `Array.from` for backward compatibility
// to convert `$images` into a real array
// so you can use `forEach` method on it
// use in conjunction with a polyfill
// for example: www.polyfill.io
const images = Array.from($images);
const $buttons = document.querySelector('.buttons');
// counter for current img
let current = 0;
// listen to click events on `$buttons` div
$buttons.addEventListener('click', function(e){
// loop through all images
images.forEach(function(img){
// hide all images
img.classList.remove('active');
});
// if the current clicked button
// contain the class "next"
if (e.target.classList.contains('next')) {
// increment counter by 1
current++;
// reset the counter if reach last img
if (current >= images.length) {
current = 0;
}
// show current img
images[current].classList.add('active');
}
// if the current clicked button
// contain the class "prev"
else {
// decrease counter by 1
current--;
// if "prev" is pressed when first img is active
// then go to the last img
if (current < 0) {
current = images.length - 1;
}
// show current img
images[current].classList.add('active');
}
});
img {
position: absolute;
top: 40px;
opacity: 0; /* hide images */
transition: opacity 1s ease-in-out;
}
.active {
opacity: 1;
}
<img class="active" src="https://dummyimage.com/100x100/e62020/fff&text=IMG1" alt="img1">
<img src="https://dummyimage.com/100x100/20e679/fff&text=IMG2" alt="img2">
<img src="https://dummyimage.com/100x100/4120e6/fff&text=IMG3" alt="img3">
<div class="buttons">
<button class="prev">Prev</button>
<button class="next">Next</button>
</div>
If you look for the easiest solution there is one. All that code added by other users look difficult for me. You can add simple html code with text to each slide and write "1/4", "2/4" etc. Even if you have 10 slides it may be easier than to implement huge jquery or javascript.
The example can be found here W3Schools slideshow
Another very common solution is to use bullet navigator. Many global companies use this solution because it is very easy to understand for everybody. Example - if you have 5 slides you have 5 bullets in the center bottom part of an image. If slide #3 is visible at the moment, third bullet changes color to indicate that you are on slide #3.
There are a few websites that create the entire html/css/js for sliders and you can customize it as you want.
Example of a page: Jssor.com
I have a div containing images and I want to show all of the inside image's titles onmouseover.
So, I have something like this :
<div id=MyDiv onmouseover="highlight(this);">
And my javascript :
function highlight(element) {
for (var i = 0; i < element.children.length; i++) {
if (element.children[i].tagName == "IMG")
element.children[i].title.show();
}
}
But all i get is a message - Object "X" has no method show.
You are using plain JavaScript. title is a string, and as the message says, it has no method show.
If what you want to do is alert all the titles in a pop-up, you can do this:
function highlight(element) {
for (var i = 0; i < element.children.length; i++) {
if (element.children[i].tagName == "IMG")
alert(element.children[i].title);
}
}
If, on the other hand you want to show them on your page you need something like this:
function highlight(element) {
var outputelement = document.getElementById("idofsomeelementyouhaveonyourpage");
for (var i = 0; i < element.children.length; i++) {
if (element.children[i].tagName == "IMG")
outputelement.innerHTML += element.children[i].title;
}
}
Of course, with the second method, you'd need an onmouseout handler that hides the titles as well.
Here is an example using jQuery:
HTML:
<div id="MyDiv">
<img src="http://chandra.harvard.edu/photo/2012/m101/m101_xray_thm100.jpg" title="img1" />
<img src="http://passport-cdn.mobilenations.com/avatars/000/004/072/100x100_4072871.jpg?r=1" title="img2" />
</div>
jQuery:
$("#MyDiv").mouseenter(function () {
$mydiv = $(this);
$.each($('img', $mydiv), function () {
var pos = $(this).position();
$('<div>', {
class: 'imgtitle'
}).css({
position: 'absolute',
color: 'red',
top: pos.top + 5,
left: pos.left + 5
})
.html($(this).attr('title'))
.insertAfter($(this));
});
}).mouseleave(function () {
$('.imgtitle').remove();
});
Here's a jsfiddle showing it in action: http://jsfiddle.net/obryckim/k5hcJ/
Hi i have written this code to take 3 parameters and assign to variable.now i want to append the text i am getting throughparameter to div fontdiv
how to do this?
here is what i have tried..
function getTextWidth(text, fontname, fontsize) {
var elem = '<div id="fontdiv" style="position: absolute;visibility: visible;height: auto;"></div>';
$('body').append($(elem));
var fontdiv = document.getElementById('fontdiv');
fontdiv.style.fontSize = fontsize;
fontdiv.style.fontFamily = fontname;
$("#fontdiv").html($('text').val());
return fontdiv.clientWidth;
};
If your text param already has text
$("#fontdiv").append(text); // append text into fontdiv
If the value of text is set already (and it seems to be), use :
$("#fontdiv").append(text);
And it should work.
Use
function getTextWidth(text, fontname, fontsize) {
var elem = '<div id="fontdiv" style="position: absolute;visibility: visible;height: auto;"></div>';
var el = $(elem).append(text);
$('body').append(el);
var fontdiv = document.getElementById('fontdiv');
fontdiv.style.fontSize = fontsize;
fontdiv.style.fontFamily = fontname;
$("#fontdiv").html($('text').val());
return fontdiv.clientWidth;
};
Another way could be
function getTextWidth(text, fontname, fontsize) {
var el = $('<div>', {
id: 'fontdiv'
}).css({
position: 'absolute',
visibility: 'visible',
height: 'auto',
fontSize: fontsize,
fontFamily: fontname
}).append(text).appendTo('body');
return el.get(0).clientWidth;
};
Replace
$('body').append($(elem));
with
$('body').append(elem);
I've written the jQuery you'll see below for a little project I'm working on. It works perfectly and is all set, but, as you can see, it's messy and kind of...long winded.
I've tried a bunch of different ways to clean this up but I'm not just ninja-like enough to really neaten it up. Any advice? Thanks in advance guys!
var colspan = $(".col header span"),
rowspan = $(".row header span"),
topspan = $(".top header span");
var colh2 = $(".col header h2").h2width();
var rowh2 = $(".row header h2").h2width();
var toph2 = $(".top header h2").h2width();
var colwidth = 820 - colh2;
var rowwidth = 820 - rowh2;
var topwidth = 820 - toph2;
colspan.css({float: 'left', width: colwidth});
rowspan.css({float: 'left', width: rowwidth});
topspan.css({float: 'left', width: topwidth});
["col", "row", "top"].forEach(function (className) {
var str = "." + className + " header";
var h2s = document.querySelectorAll(str + " h2");
var spans = document.querySelectorAll(str + " span");
var width = 820 - h2width(h2s);
Array.prototype.forEach.call(spans, function (span) {
span.style.float = "left";
span.style.width = width;
});
});
Because jQuery is always overkill.
I would do it like this maybe? shorter but maybe not as well documented:
$(".col header span, .row header span, .top header span").each(function(){
$(this).css({
float: 'left',
width: 820 - $(this).siblings("h2").width()
});
});
I would probably rewrite your code in the following way:
var conts = {
'col': jQuery('.col header'),
'row': jQuery('.row header'),
'top': jQuery('.top header')
};
jQuery.each(conts, function(index, val){
val.find('span').css({
'float': 'left',
'width': 820-val.find('h2').h2width()
});
});
This uses caching the main elements and then will iterate on all of them applying the similar actions.
See more information on jQuery's .each() function.
EDIT: Or even shorter:
jQuery('.col header, .row header, .top header').each(function(){
var current = jQuery(this);
current.find('span').css({
'float': 'left',
'width': 820 - current.find('h2').h2width()
});
});
Simply get rid of the duplicate code:
$.each(['.col', '.row', '.top'], function(i, cls) {
var width = $(cls + ' header h2').h2width();
$(cls + ' header span').css({
float: 'left',
width: 820 - width
});
});
Just use a function:
function updateStyle(name){
var headerSpan = $('.' + name + ' header span');
var headerH2 = $('.' + name + ' header h2');
headerSpan.css({float: 'left', width: 820 - headerH2.h2width()});
}
updateStyle('col');
updateStyle('row');
updateStyle('top');