Prepend next element to div - javascript

I´m trying to prepend a div (.portrait_text) to a container (.gallery_container):
Every image gets prepended to its corresponding .gallery_container. but I want to aslo prepend every next .portrait_text div to it´s .gallery_container. Any ideas?
<div id="gallery_images_inner" class="clearfix">
<img src="img/portrait.jpg" alt="portrait" width="850" height="557">
<div class="portrait_text">Girls After Swim</div>
<img src="img/gallery5.jpg" alt="gallery5" width="850" height="566">
<div class="portrait_text">Girls After Swim</div>
</div>
JS:
function Gallery(selector) {
this.add_module = function (type, image) {
var container = $('<div />', {
'class': 'gallery_container'
}).append(image);
if (type == 'horizontal') {
var h_ar = image.attr('height') / image.attr('width');
var c_width = selector.width();
var c_height = selector.width() * h_ar
container.css({
'width': c_width - 60,
'height': c_height
})
}
if (type == 'vertical') {
var c_width = v_width;
var c_height = v_height
container.css({
'width': Math.floor(v_width) - 30,
'height': v_height
})
}
container.css({
'float': 'left',
'overflow': 'hidden'
})
container.find('img').attr({
'width': '100%',
'height': '100%'
})
container.attr('ar', c_height / c_width)
container.appendTo(selector);
//container.children('img').fitToBox();
}
}

If image is being passed as a jQuery object, as your code seems to suggest, you can use .next() to select the text as well:
function Gallery(selector) {
this.add_module = function (type, image) {
var portrait_text = image.next('.portrait_text');
var container = $('<div />', {
'class': 'gallery_container'
}).append(image).append(portrait_text);
...
}
}
Of course, this is appending and you asked for prepending, but the concept is the same.

jQuery has a next selector, so you can do
$(selector).next(".portrait_text").appendTo(container);

Related

Hiding Arrows Based on Horizontal Scroll

I'm struggling to make a tiny change in this horizontal scroll code: http://jsfiddle.net/Lpjj3n1e/
I want to make the right button disappear when you scroll all the way to the right (just like it happens with the left button in the original code).
There should be a quick and easy solution but I haven't been able to find one. Please help me and thank you in advance!
$(function() {
var print = function(msg) {
alert(msg);
};
var setInvisible = function(elem) {
elem.css('visibility', 'hidden');
};
var setVisible = function(elem) {
elem.css('visibility', 'visible');
};
var elem = $("#elem");
var items = elem.children();
// Inserting Buttons
elem.prepend('<div id="right-button" style="visibility: hidden;"><</div>');
elem.append(' <div id="left-button">></div>');
// Inserting Inner
items.wrapAll('<div id="inner" />');
// Inserting Outer
debugger;
elem.find('#inner').wrap('<div id="outer"/>');
var outer = $('#outer');
var updateUI = function() {
var maxWidth = outer.outerWidth(true);
var actualWidth = 0;
$.each($('#inner >'), function(i, item) {
actualWidth += $(item).outerWidth(true);
});
if (actualWidth <= maxWidth) {
setVisible($('#left-button'));
}
};
updateUI();
$('#right-button').click(function() {
var leftPos = outer.scrollLeft();
outer.animate({
scrollLeft: leftPos - 200
}, 800, function() {
debugger;
if ($('#outer').scrollLeft() <= 0) {
setInvisible($('#right-button'));
}
});
});
$('#left-button').click(function() {
setVisible($('#right-button'));
var leftPos = outer.scrollLeft();
outer.animate({
scrollLeft: leftPos + 200
}, 800);
});
$(window).resize(function() {
updateUI();
});
});
The main problem seems to be that on clicking the left button there is no function to check whether the arrow should be removed or not.
To test for this we can use the actualWidth which has already been calculated (but it needs to be made more global so its declaration has moved).
There is another small thing which needs rectification - if the maxWidth is greater than the actualWidth there is no need for the arrows. In the code below therefore setVisible has become setVisibleIfNeeded
Here is the revised JS - the original was taken from the jsfiddle. There is a NOTE beside each alteration.
$(function() {
var print = function(msg) {
alert(msg);
};
var setInvisible = function(elem) {
elem.css('visibility', 'hidden');
};
var setVisibleIfNeeded = function(elem) {
if (actualWidth>maxWidth) {//NOTE we don't want to show the arrows if there is space in the div for everything without the need to scroll
elem.css('visibility', 'visible');
}
};
var elem = $("#elem");
var items = elem.children();
// Inserting Buttons
elem.prepend('<div id="right-button" style="visibility: hidden;"><</div>');
elem.append(' <div id="left-button" style="visibility: hidden;">></div>');//NOTE: visibility set to hidden
// Inserting Inner
items.wrapAll('<div id="inner" />');
// Inserting Outer
debugger;
elem.find('#inner').wrap('<div id="outer"/>');
var outer = $('#outer');
var actualWidth=0;//NOTE the declaration is moved up here from the function it was in
var maxwidth=0;//ditto
var updateUI = function() {
maxWidth = outer.outerWidth(true);
actualWidth = 0;
$.each($('#inner >'), function(i, item) {
actualWidth += $(item).outerWidth(true);
});
setVisibleIfNeeded($('#left-button'));
};
updateUI();
$('#right-button').click(function() {
setVisibleIfNeeded($('#left-button'));//NOTE added
var leftPos = outer.scrollLeft();
outer.animate({
scrollLeft: leftPos - 200
}, 800, function() {
debugger;
if ($('#outer').scrollLeft() <= 0) {
setInvisible($('#right-button'));
}
});
});
$('#left-button').click(function() {
setVisibleIfNeeded($('#right-button'));
var leftPos = outer.scrollLeft();
outer.animate({
scrollLeft: leftPos + 200
}, 800,function() {//NOTE function added here to get rid of left button
if (leftPos>=(actualWidth-400)) {setInvisible($('#left-button'));}
});
});
$(window).resize(function() {
updateUI();
});
});

How to get image to original position

Fiddle:
https://jsfiddle.net/r73b14y5/3/
script works fine but cant get the image to slide back to the original location if another link is not clicked.
at the moment the image stays where ever it last hovered over, instead of only staying at a link if the new link was clicked. and sliding back to the original link if nothing is clicked.
Also whats the best way to delay the hover state so as the mouse flys over the element quickly it doesnt activate. hover intent.
HTML:
<div class="bblock1" style="height:100%;">
<div class="container">
<div class="bodymainMaxS">
<div class='tabbed_content'>
<div class='tabs'>
<div class='moving_bg'> </div>
<span class='tab_item tab_item_color'>OVERVIEW</span>
<span class='tab_item'>THE SCIENCE</span>
<span class='tab_item'>ORDER</span>
<span class='tab_item'>REPLACEMENT FILTERS</span>
</div>
</div>
</div>
</div>
<div class="bblock3" style="height:100%;">
<div class="container">
<div class="bodymainMaxS">
</div>
</div>
</div>
** key part of Script:**
$(".tab_item").mouseover(function() {
var $this = $(this);
$this.parent().find(".moving_bg").stop().animate({
left: $this.position()['left']
}, { duration: 300 });
});
rest of script
var TabbedContent = {
current: {i:null, obj:null},
init: function() {
$(".tab_item").click(function() {
$(".tab_item").removeClass("tab_item_color");
$(this).addClass("tab_item_color");
var $this = $(this);
TabbedContent.slideContent($this);
});
TabbedContent.current.i = 0;
TabbedContent.current.obj = $(".tabslider li").eq(0);
},
slideContent: function($obj) {
var $container = $obj.closest(".tabbed_content"),
$contentContainer = $('.bodymainMaxS'),
$tabslider = $contentContainer.find(".tabslider");
var i = $obj.index() - 1;
var $lis = $tabslider.find("li");
$new = $lis.eq(i);
if(i === TabbedContent.current.i) {
return;
}
$lis.hide().filter($new.add(TabbedContent.current.obj)).show();
var margin_1 = (i > TabbedContent.current.i) ? 0 : -$new.width();
var margin_2 = (i < TabbedContent.current.i) ? 0 : -$new.width();
$tabslider.stop().css({
marginLeft: margin_1 + "px"
}).animate({
marginLeft: margin_2 + "px"
}, 400);
TabbedContent.current.i = i;
TabbedContent.current.obj = $new;
}
}
TabbedContent.init();
Here is the complete JS fixed replace whole javascript with this one (you can test here with JSFiddle )
removed TabbedContent because that was not being used (if you need that you can always copy from your question)
var isTabSelected = false;
var lastSelectedTabLeftPos;
$(".tab_item").mouseover(function() {
var $this = $(this);
$this.parent().find(".moving_bg").stop().animate({
left: $this.position()['left']
}, { duration: 300 });
});
$( ".tab_item" ).mouseout(function() {
if(isTabSelected){
$(".moving_bg").stop().animate({
left: ""+lastSelectedTabLeftPos
}, { duration: 300 });
}else
{
$(".moving_bg").stop().animate({
left: "0"
}, { duration: 300 });
}
});
$(".tab_item").click(function() {
isTabSelected = true;
var $this = $(this);
lastSelectedTabLeftPos = $this.position()['left'];
});

kendo ui resize column

I am using the following function(which i got from web) to resize the column in kendo ui.
this is based on Index, i am looking out to see if there can be an option to select by column title or field/key.
when i reorder the grid column, this function fails.
function resizeColumn(idx, width) {
$("#grid .k-grid-header-wrap") //header
.find("colgroup col")
.eq(idx)
.css({ width: width });
$("#grid .k-grid-content") //content
.find("colgroup col")
.eq(idx)
.css({ width: width });
}
To resize by column title, you just need to figure out the correct index, e.g. like this:
function resizeColumn(title, width) {
var index = $("#grid .k-grid-header-wrap").find("th:contains(" + title + ")").index();
$("#grid .k-grid-header-wrap") //header
.find("colgroup col")
.eq(index)
.css({ width: width });
$("#grid .k-grid-content") //content
.find("colgroup col")
.eq(index)
.css({ width: width });
}
Search column by field id to make sure that is the corrected field.
function resizeColumn(fieldId, width) {
var index = $('#grid .k-grid-header-wrap').find('th[data-field="' + fieldId + '"]').index();
$("#grid .k-grid-header-wrap") //header
.find("colgroup col")
.eq(index)
.css({ width: width });
$("#grid .k-grid-content") //content
.find("colgroup col")
.eq(index)
.css({ width: width });
}
click here to get complete Answer
Loading Column State
function loadColumnState(columnStateKey: string, realGrid): void
{
var colState = JSON.parse($.jStorage.get(columnStateKey));
if(colState && colState.length > 0)
{
var visibleIndex = -1;
for (var i = 0; i < colState.length; i++)
{
var column = colState[i];
// 1. Set correct order first as visibility and width both depend on this.
var existingIndex = -1;
if (typeof column.field !== 'undefined')
{
existingIndex = findFieldIndex(realGrid, column.field);
}
else if (typeof column.commandName !== 'undefined')
{
existingIndex = findCommandIndex(realGrid, column.commandName);
}
if (existingIndex > -1 && existingIndex != i) // Different index
{ // Need to reorder
realGrid.reorderColumn(i, realGrid.columns[existingIndex]);
}
// 2. Set visibility state
var isHidden = (typeof column.hidden === 'undefined') ? false : column.hidden;
if (isHidden)
{
realGrid.hideColumn(i);
}
else
{
realGrid.showColumn(i);
++visibleIndex;
}
// 3. Set width
var width = (typeof column.width === 'undefined') ? null : column.width;
if(width != null)
{
realGrid.columns[i].width = width; // This sets value, whilst rest redraws
realGrid.thead.prev().find('col:eq(' + visibleIndex + ')').width(width);
realGrid.table.find('>colgroup col:eq(' + visibleIndex + ')').width(width);
}
}
}
}

How to show all div's inside images titles onmouseover?

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/

How to append text to div

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);

Categories