Trying to change 'margin-top' attribute - javascript

This is what I'm trying to do :
$(function(){
$('div.item').css('margin-top',-(closest('img').height())/2+'px');
});
I want my '<div class="item"'>
to get style="margin-top:XXXXXX; top:50%"
where 'XXXXXX' is equal to (('div.item a img').height())/2
======================================================
EDIT : ( solved )
Final code for those who are interested :
<script type="text/javascript">
$(function(){
theWindow.resize(function() {
$('div.item').each(function(i){
$(this).css('top',(($(window).height())/2)-(($(this).first('img').height())/2)+'px');
});
}).trigger("resize");
});
</script>
( i used only top attribute instead of top + margin-top )
Thanks for help

I think this might be what you need, especially if you have more than one div.item
$('div.item').each(function(){
var r = $(this).find('img').first().height();
$(this).css('margin-top', r/2 + 'px');
});
EDIT
You need to .find() the img and then select the .first() one.
Example: http://jsfiddle.net/jasongennaro/JNMhC/3/

From what I can tell, you are trying to do something like this :
$(function(){
$('div.item').css('margin-top',-($('div.item').closest('img').height())/2+'px');
});
But the image selector depends on your html configuration.
If you post some html markup, maby I could provide a better solution.

Related

Targetting and Changing HTML content using jQuery

I'm trying to change the "10" in the HTML below using jQuery:
<div id="ingredients">
<h2>Ingredients</h2>
<h4>Sugar: <span class="sugar">10</span></h4>
Here have been the iterations that I've gone through that have been unsuccessful:
$(document).ready(function() {
$('#ingredients.sugar').html("5");
});
and
$(document).ready(function() {
$('span[class=sugar]').html("5");
});
In addition, how would I store the value of "10" in a variable? I'm trying to do this:
var $sugar = $('#ingredients.sugar').html();
Would that work?
Thanks!
Henry
Try:
$(document).ready(function() {
$('#ingredients .sugar').html("5");
});
Notice the space between; this says look for a .sugar child from the #ingredients parent. You should also be able to do:
var val = $('#ingredients .sugar').html();
You have missed space in your selector, this will work:
$('#ingredients .sugar').html("5");
Here's a version with a simplified selector (don't need #ingredients), factory caching and update without using quotes (5 works fine).
// Document ready
$(function () {
var $sugar = $( '.sugar' ), // Cache jQuery factory
originalValue = $sugar.html(); // Cache original value
// Update value
$sugar.html( 5 );
});

execCommand insertHtml, outer div not inserted why?

Why is the DIV not inserted but only the IMG ?
$(document).ready(function() {
$(document).on('click', '#insertImage', function(){
/*
Why is the DIV not inserted ?
*/
var item = "<div class='resizable'><img src='http://www.rockiesventureclub.org/wp-content/uploads/2013/02/flower-icon.png'></div>";
document.execCommand('insertHTML', false,item);
})
});
see:
http://jsfiddle.net/daslicht/gU2jP/#base
Why not doing it with jQuery since you already use it??
http://jsfiddle.net/gU2jP/5/
var _$div = $('<div>'),
_$img = $("<img class='resizeable' id='myImg' src='http://imperavi.com/img/library.jpg' />");
_$div.append(_$img);
$('body').append(_$div);
The background of the Question was the following:
I just like to be able to make the added Image Float Left or Right.
Since jQueryUI automatically adds a wrapper-div around each resizeable item I thought that I need to add it somehow manually in order to assign a id to it.
doug65536 on Freenode helped me to create this solution without the need to create an additionally div manually:
We also discovered that the Fiddle wont work properly in safari
$(document).on('click', '#insertImage', function () {
document.execCommand('insertHTML', false,
"<img class='resizeable' id='myImg' src='http://imperavi.com/img/library.jpg'>");
$(".resizeable").resizable({
aspectRatio: true
}); //just a try here
$('#myImg').parent().css({
'float':'left',
'margin':'15px'
});
})
http://jsfiddle.net/daslicht/6cGbQ/
Thank you very Much !

Hashtag to trigger a jQuery animation

I have received help earlier in another question about some jQuery transitioning and I got my website to behave properly, but now I need to get a bit deeper into this jQuery transitioning...
I need a particular effect/transition to happen based on the hashtag that is written in the address bar. This is the code provided by the other question by pckill:
$('.nav').on('click', 'li', function(){
var id = $(this).data('id');
var breadcrumbs = document.getElementById('breadcrumbs');
breadcrumbs.innerHTML = 'IMGit » <span class="capitalize">' + id + '</span>';
var current = $('#inner').find('[data-page=' + id + ']');
if (current.hasClass('hidden'))
{
current.css('marginLeft', '-200%');
$('#inner > div').not(current).animate(
{marginLeft: '100%'},
'fast',
function(){
$('#inner > div').not(current).addClass('hidden');
current.removeClass('hidden');
current.animate({marginLeft: '0%'}, 'fast');
});
}
});
And this is the HTML: http://pastebin.com/pu7jmefC
Let's say, for example, I link someone to http://mywebsite.com/index.php#remote, I want the user to be transitioned with jQuery to the proper div. The approach above works perfectly with the menu I have, but I want to be able to share the URL with someone and they'd still be able to get directly to the proper div.
I think the code above needs some altering to make it do what I seek, but I unfortunately, I'm not that good in Javascript/jQuery.
I guess we'd have to touch the code somewhere around here: $('#inner > div').not(current).
I know we have window.location.hash to work with hashtags, but I have no idea how to put it to use in the code above.
Ideas?
If you just need to check the hash on page load and perform an action accordingly, that's really simple. First of all you need to move the logic of transitioning to a div into a separate function, say transitionToDiv:
function transitionToDiv(id) {
var current = $('#inner').find('[data-page=' + id + ']');
if (current.hasClass('hidden'))
{
current.css('marginLeft', '-200%');
$('#inner > div').not(current).animate(
{marginLeft: '100%'},
'fast',
function(){
$('#inner > div').not(current).addClass('hidden');
current.removeClass('hidden');
current.animate({marginLeft: '0%'}, 'fast');
});
}
}
And change the click event (the code in your question) to:
$('.nav').on('click', 'li', function() {
var id = $(this).data('id');
var breadcrumbs = document.getElementById('breadcrumbs');
breadcrumbs.innerHTML = 'IMGit » <span class="capitalize">' + id + '</span>';
transitionToDiv(id);
}
Now, to transition to a div on page load based on the address hash, simply add these lines at some point after page load:
var id = window.location.hash.substr(1);
transitionToDiv(id);

"Tooltip" jQuery plugin breaks

I'm working on a very light "tooltip" jQuery plugin. Bellow is the code:
(function( $ ) {
$.fn.tooltip = function() {
return this.each(function(){
var target = $(this);
target.on("mouseover", function(event){
var tooltip = $(document.createElement("div"));
tooltip
.html(target.attr("tooltip-text"))
.addClass("tooltip")
.css({
"top" : event.pageY,
"left":event.pageX
})
.fadeIn(300);
});
});
};
})( jQuery );
And I apply it like so:
<script>
$("div.product").tooltip();
</script>
The idea is to have the tooltip appear when the user hovers the DIV, next to the cursor.
However, when I hover such a DIV (class "product"), the script crashes at the .addClass("tooltip") line:
Uncaught TypeError: Object has no method 'addClass'
What is it that I'm doing wrong?
It's because you're assigning the attribute tooltip-text:
.html(target.attr("tooltip-text"))
The attribute is undefined, so it screws up the chaining of your jQuery events. Try doing this:
.html(target.attr("tooltip-text") || "")
You also don't need to stick the execution in window.onload, putting it in a standard document ready will work fine.
Do not know why but use
.attr("style", tooltip.attr("style") + " tooltip")
instead of .addClass.
Hope this helps.

jQuery toggle() text in separate element

I am having some trouble getting a toggle function to work and need someone to help explain it to me.
My HTML (simplified):
<div id="filter_names"></div>
<div class="item">Option 1</div>
<div class="item">Option 2</div>
<div class="item">Option 3</div>
<div class="item">Option 4</div>
My jQuery (simplified)
$(".item").click(function(){
var tagname = $(this).html();
$('#filter_names').append(' > '+tagname);
$(".loading").show();
});
As you can see I am appending clicked items' value to the div at the top. This works fine, but i need it to be removed when i click it again.
I am pretty sure it needs a toggle() function but so far my attempts have been pretty fruitless.
Some guidance would be greatly appreciated.
EDIT: You can see what i want to achieve in this JSfiddle. It's working exactly how i want it to by appending a value to the end (like a breadcrumb link), but is not being removed when i click it again.
You need to look at the #filter_names contents and check if the clicked tag's value is already included, then remove it if it is, or add it otherwise:
if (filternames.indexOf(tagname) === -1) {
$('#filter_names').append(' > '+tagname);
} else {
$('#filter_names').text(filternames.replace(' > '+tagname, ''));
}
Working fiddle: http://jsfiddle.net/passcod/Kz3vx/
Note that you might get weird results if one tag's value is contained in another's.
<script type="text/javascript">
$(function(){
$(".item").click(function(){
var $this=$(this);
var tagname = ' > ' +$this.html();
//if has item-check class remove tag from filter_names
if($this.hasClass("item-click")){
var h=$("#filter_names").text();
$("#filter_names").text(h.replace(tagname, '' ));
}
else{
$('#filter_names').append(tagname);
}
$(this).toggleClass("item-click").toggleClass("item");
});
});
</script>
try this one...
$(this).toggleClass("item-click item");
this will add these classes alternatively when you click on div. or if you just want to remove this class on second click then you should write this in your click handler.
if( $(this).hasClass("item-click")){
$(this).removeClass("item-click");
}
EDITED -----
to remove appended html you can try this...
if($(this).hasClass("item-click")){
$("#filter_names").text("");
}
else{
$('#filter_names').append(tagname);
}
it's working HERE
hope this helps you!!
I like passcod's solution - here's an alternative that wraps the elements in divs and puts them in alphabetical order.
JSFiddle here. The sort function is from http://www.wrichards.com/blog/2009/02/jquery-sorting-elements/.
$(".item").click(function(){
var tagname = $(this).html();
var target = $('#filter_names').find('div:contains("> ' + tagname + '")');
if (target.is('*')) {
target.remove();
}
else $('#filter_names').append('<div class="appended"> > '+ tagname +'<div>');
function sortAlpha(a,b) {
return a.innerHTML > b.innerHTML ? 1 : -1;
}
$('#filter_names div').sort(sortAlpha).appendTo('#filter_names');
});

Categories

Resources