Check if image has title attribute, then apply to image selector - javascript

This doesn't seem to be working for me. I want to perform these actions only on images with a title attribute set. It seems my problem is when I use $(this), it is referring to the title attribute? Thanks in advance.
(function($) {
$(function() {
/* Run this only if images have a title attribute */
if ($('.node-page img[title], .node-news img[title]')) {
$(this).each(function() {
var image = $(this);
var caption = image.attr('title');
var imagealign = image.css('float');
image.after('<span class="caption">' + caption + '</span>');
image.next('span.caption').andSelf().wrapAll('<div>');
image.parent('div').addClass('caption-wrapper').css({'width': imagewidth, 'height': 'auto', 'float': imagealign});
});
}
});
})(jQuery);

It seems you got mixed-up with the if and the each(). You should apply your each to your selector directly. If no image have a title attribute then it won't do anything, else it will apply your function to each element.
(function($) {
$(function() {
/* Run this only on images that have a title attribute */
$('.node-page img[title], .node-news img[title]').each(function() {
var image = $(this);
var caption = image.attr('title');
var imagealign = image.css('float');
image.after('<span class="caption">' + caption + '</span>');
image.next('span.caption').andSelf().wrapAll('<div>');
image.parent('div').addClass('caption-wrapper').css({'width': imagewidth, 'height': 'auto', 'float': imagealign});
});
});
})(jQuery);

Related

Background image is not added through javascript

I am trying to use modernizr so I javascript can detect if the browser supports object-fit and object-position. The code I got from modernizr works fine, but if it detects something like no-object-fit I want to execute this bit of code:
if (!Modernizr.objectfit) {
$('.wrapper__figure').each(function() {
var $container = $(this),
imgUrl = $container.find('img').prop('src');
if (imgUrl) {
$container
.css('background-image', 'url(' + imgUrl + ')');
}
});
}
I don't seem to get this working. No changes are made inside of the browser if I check in developer mode(I am only testing this in IE. All the other browsers don't need this). I think that it has something to do with adding .css('background-image', 'url(' + imgUrl + ')'); to the $container, but I am not realy sure if this is the case or something else
Its attr not prop - because src is an attribute, not a property.
if (Modernizr.objectfit) {
$('.wrapper__figure').each(function() {
var $container = $(this),
imgUrl = $container.find('img').attr('src');
if (imgUrl) {
$container.css('background-image', 'url(' + imgUrl + ')');
}
});
}

Add width and height attr to all images

I need width and height attributes added to all images on a page via javascript/jquery. This is due to a tool our systems use. I thought a simple each loop, adding height/width attr would suffice. Unfortunately this doesn't seem to work
DEMO https://jsfiddle.net/z86xnqd7/
$('body').find('img').each(function (index) {
var theWidth = index.width();
var theHeight = index.height();
index.attr({
"width": theWidth,
"height": theHeight
});
});
When you inspect element you will notice no width/height attr has been added
jsFiddle : https://jsfiddle.net/CanvasCode/z86xnqd7/6/
You need to do your each on the load event, you need to make sure your image has loaded before you check its height and width. Also you want to use $(this) instead of index.
$(function () {
$('img').load(function () {
var theWidth = $(this).width();
var theHeight = $(this).height();
$(this).attr({
"width": theWidth,
"height": theHeight
});
});
});
It's because index is real iteration index (e.g. 1, 2...). Use $(this) or add second parameter to function header function (index, element) {}:
$.each($('img'), function () {
$(this).attr({
width: $(this).width(),
height: $(this).height()
});
});
Problem here is that you try to get the width and height from the index which is just a number and no jQuery object. Try this - it will do the job:
$('body').find('img').each(function(i, elem) {
var $this = $(this);
var theWidth = $this.width();
var theHeight = $this.height();
$this.attr({"width": theWidth, "height": theHeight});
});
See js fiddle: https://jsfiddle.net/g4nn2pk0/2/

Link inside created DIV cause the div removed on hover

Here is my code:
var tagDes = document.createElement('DIV');
tagDes.className = 'tagDes';
tagDes.style.cssText = 'position:absolute;'+
'background:#282828;'+
'color:#fff;'+
'padding:10px;'+
'top:'+(posX+hei)+'px;'+
'left:'+(posY+wid)+'px;'+
'font-size:10pt;';
tagDes.onmouseout = function(){
$(this).remove();
};
$('#main-container').append(tagDes);
$('.tagDes').append(array[5]+'<a class="tagMenu">sdsdssds</a>');
posX, posY, hei, wid is reffering to an element for positioning. array[5] is a string.
I want to hover for a li and create div that contain link(tagMenu class) inside(looks like title attribute). But when I hover the link inside that div, the div will remove(). What I looking for is when I hover the link the div still visible and it will removed from page when I mouseout from it. Any suggestion? Please help me.
try something like this:
tagDes.onmouseout = function(e){
if (e.toElement.parentNode == this || e.toElement == this) {
return;
}
$(this).remove();
};
If I understood you correctly you want to bind onmouseout event to inner link element. Then the code can be like this (I made use of more jQuery to simplify it):
var $tagDes = $('<div class="tagDes"></div>').css({
background: '#282828',
color: '#fff',
padding: '10px',
top: (posX + hei) + 'px',
left: (posY + wid) + 'px',
fontSize: '10pt'
})
.append(array[5] + '<a class="tagMenu">sdsdssds</a>')
.appendTo('#main-container');
$tagDes.on('mouseleave', function() {
$tagDes.remove();
});

Accessible and dynamic animated information box

I have started with the example and added to the code to make it:
Dynamic in height
Accessible with JS turned off
Have I done this correct? Will this work on most browsers?
Working version visable here:
Original:
$('#example-links a').hover(function(){
var index = $("#example-links a").index(this);
$('#example-content').animate({"marginTop" : -index*220 + "px"}); // multiply by height+top/bottom padding/margin/border
});
My modified code, it just seems a little long compared to the above:
var maxHeight = 0, container_maxHeight = 0;
var example_content = $("#example-content");
var example_div = example_content.children("div");
example_div.each(function() {
if($(this).height() > maxHeight) {
maxHeight = $(this).height();
container_maxHeight = $(this).outerHeight(true);
}
});
example_div.height(maxHeight);
$("#example-content-container").css({
"overflow":"hidden",
"height": container_maxHeight+"px"
});
$('#example-links a').bind('click mouseover', function(e){
var index = $("#example-links a").removeClass("active").index(this);
$(this).addClass("active");
example_content.stop().animate({"marginTop" : -index*container_maxHeight + "px"});
e.preventDefault();
});
I bind both the click and mouseover because I want it to work via mouseover but then I also want it to work when browsing on a mobile phone that doesn't have a mouse to activate the hover.
Everything seems fine, the only thing I would add to make it more accessible if JS is off, are the section ids. You can check it here.
For each section, you add an id to the wrapping div, and then on your side links you link to that id.
I would clean up your code a little bit more:
(function($){
$(document).ready(function(){
var maxHeight = 0, container_maxHeight = 0,
example_content = $("#example-content"),
example_div = example_content.children("div");
example_div.each(function() {
var $section = $(this);
if($section.height() > maxHeight) {
maxHeight = $section.height();
container_maxHeight = $section.outerHeight(true);
}
});
example_div.height(maxHeight);
$("#example-content-container").height(container_maxHeight);
var $tabs = $('#example-links a');
$tabs.bind('click mouseover', function(e){
var index = $tabs.removeClass("active").index(this);
$(this).addClass("active");
example_content.stop().animate({"marginTop" : -index*container_maxHeight + "px"});
e.preventDefault();
});
});
})(jQuery);

unable to get tooltip to work when usingjQuery load() content

I am having problem getting my tooltip to work when using the jQuery load() function. The tooltip works fine if i don't use load() to load external dynamic data.
I googled and found the i may need to use live(), but I can't figure how to get it to work. Any suggestion?
thank you!!
Here is my scripts:
function loadEMERContent(uid) {
$("#ActionEWPNBook").load("ajaxLoadDATA.cfm?uid="+uid, null, showLoading);
$("#EWPNBookloading").html('<img src="/masterIncludes/images/ajaxLoading.gif" alt="loading" align="center" />');
}
function showLoading() {
$("#EWPNBookloading").html('');
}
function simple_tooltip(target_items, name){
$(target_items).each(function(i){
$("body").append("<div class='"+name+"' id='"+name+i+"'><p style='padding:5px;'>"+$(this).attr('title')+"</p></div>");
var my_tooltip = $("#"+name+i);
$(this).removeAttr("title").mouseover(function(){
my_tooltip.css({opacity:0.8, display:"none"}).stop().fadeIn(400);
}).mousemove(function(kmouse){
my_tooltip.css({left:kmouse.pageX+15, top:kmouse.pageY+15});
}).mouseout(function(){
my_tooltip.stop().fadeOut(400);
});
});
}
Here is my ajaxLoadDATA.cfm: it returns an unorder list
<li><span title="dynamic title here" class="tipthis">date</span></li>
In your callback function, you need to run the tooltip code against the new items, like this:
function showLoading(data) { //data = the response text, passed from `.load()`
$("#EWPNBookloading").html('');
var items = //get items here, something like $('.giveMeATooltip', data);
var name = //set name, not sure what you're using for this
simple_tooltip(items, name);
}
One side tip, if you change this line:
$("body").append("<div class='"+name+"' id='"+name+i+"'><p style='padding:5px;'>"+$(this).attr('title')+"</p></div>");
To something like this:
$("body").append(
$("<div></div>", { 'class': name, 'id': name + i }).append(
$("<p style='padding:5px;'></p>").text($(this).attr('title'))
)
);
Your tooltip generation will be much faster due to how jQuery can cache document fragments for reuse.
I use a modified version of this tooltip. This version uses .live so loaded content will automatically have tooltip functionality. All you need to do is:
Add this script to your main page (adding it as an external file is perferred)
You need to ensure that the elements that need a tooltip have a class="tipthis" and that the tooltip contents are within the title attribute. Also, the tooltip can contain HTML (e.g. <h1>Tooltip</h1>Hello,<br>World).
You will also need some basic CSS:
#tooltip { background: #f7f5d1; color: #333; padding: 5px; width: 300px; }
Here is the script (using live and it requires jQuery version 1.4+)
/* Tooltip script */
this.tooltip = function(){
// Defaults
var tooltipSpeed = 300; // fadein speed in milliseconds
var xOffset = 20; // Don't use negative values here
var yOffset = 20;
$('.tipthis').live('mouseover',function(e) {
this.t = this.title;
this.title = '';
$('<div></div>', {
id : 'tooltip',
css: {
display : 'none',
position: 'absolute',
zIndex : 1000,
top : (e.pageY - xOffset) + 'px',
left : (e.pageX + yOffset) + 'px'
}
})
.html( this.t )
.appendTo('body');
$('#tooltip').fadeIn(tooltipSpeed);
})
.live('mouseout',function(){
this.title = this.t;
$('#tooltip').remove();
})
.live('mousemove',function(e){
$("#tooltip").css({
top : (e.pageY - xOffset) + 'px',
left: (e.pageX + yOffset) + 'px'
});
})
}
$(document).ready(function(){ tooltip(); });
Here is some sample HTML:
Hover over me!

Categories

Resources