jQuery Newbie, need a little help - javascript

Okay, so I am in the process of recreating this feature:
http://www.w3.org/html/logo/#the-technology
I current have it so when you click on a link, it will add a class to the image that relates to that link (href="#one" on the <a> and then id="#one" on the <img>), however it is currently not going through each <a> tag and only one. And also it is not removing the class I requested.
Code follows:
JS
$(document).ready(function() {
var container = '#portfolio #text_container';
var img_container = '#portfolio #image_container';
$(container).children('a').bind('click', function() {
var this_attr = $(this).attr('href');
var this_img = $(img_container).find('img').attr('id');
if(this_attr == this_img) {
//$(img_container).find('img').hasClass('current').removeClass('current');
// ^^^ This line isn't working, any ideas? :/
$(img_container + ' img[id*="' + this_attr + '"]').addClass('current');
}
else {
alert(this_img + ' this img');
alert(this_attr + ' this attr');
}
});
});
And the HTML is as follows
<div id="portfolio">
<div id="image_container">
<img src="http://static.jquery.com/files/rocker/images/logo_jquery_215x53.gif" alt="" class="current" id="#one" />
<img src="http://static.jquery.com/files/rocker/images/btn_downloadLarge.gif" alt="" id="#two" />
</div>
<div id="text_container">
Item 1
Item 2
<p id="#one" class="current">A bunch of text!</p>
<p id="#two">The second bunch of text!</p>
</div>
</div>
Please let me know if you need any more information :)
rcravens fixed this with the following code..
JS
$(document).ready(function() {
$('#text_container a').click(function(evt) {
evt.preventDefault();
$('.current').removeClass('current');
var href = $(this).attr('href');
$("." + href).addClass('current');
});
And the HTML..
<div id="portfolio">
<div id="image_container">
<img src="http://static.jquery.com/files/rocker/images/logo_jquery_215x53.gif" alt="" class="one current" />
<img src="http://static.jquery.com/files/rocker/images/btn_downloadLarge.gif" alt="" class="two" />
</div>
<div id="text_container">
Item 1
Item 2
<p class="one current">A bunch of text!</p>
<p class="two">The second bunch of text!</p>
</div>
</div>

My interpretation of what you are trying to do is here:
http://jsfiddle.net/rcravens/wMhEC/
The code is changed a bit. You shouldn't have multiple elements with the same id.
Bob

The reason this isn't working:
if(this_attr == this_img)
is because this_attr is a URL and this_img is an ID attribute value.

Related

How to write a document.querySelector for the following code

I'm having difficulty writing the document.querySelector for the following code. Currently I've written this code as querySelector but it does not encompass everything...
Please help me improve this, thank you.
Edit: as there seemed to be some confusion, let me elaborate. I would like all the elements, from div, a, img, everything to be encompassed in the querySelector.
var areaa = document.querySelector("#menu #envelope #links");
<div id="menu">Click here to browse the internet.
<div id="envelope">
<div id="links" >
<div>
<a id="g" class="redirect">
<img id="google" src="assets/google.png" />
</a>
</div>
<div style="width: 20%;"></div>
<div>
<a id="s" class="redirect">
<img id="sava" src="assets/Logo_Sava.png"/>
</a>
</div>
</div>
</div>
</div>
Edit 2 - as more code was required (the href elements are removed / added as needed)...
var menu = document.getElementById("menu");
var areaa = document.querySelectorAll(".areaa");
menu.addEventListener("mouseenter", addHref);
//areaa.addEventListener("mouseleave", remHref);
document.addEventListener("mousemove", function(){
if(this != areaa){
remHref();
}
});
menu.addEventListener("click", addHref);
document.addEventListener("click", function (){
if (this != areaa){
remHref();
}
});
var g = document.getElementById("g");
var s = document.getElementById("s");
function remHref (){
if (g.hasAttribute("href")){
g.removeAttribute("href");
}
if (s.hasAttribute("href")){
s.removeAttribute("href");
}
}
function addHref (){
setTimeout(activate, 250);
}
function activate (){
document.getElementById("g").setAttribute("href", "https://www.google.com");
document.getElementById("s").setAttribute("href", "https://www.example.com");
}
you might want to add a class to all elements you want to be captured, then use document.querySelectorAll
var areaa = document.querySelectorAll(".my-class");
html shoud look like this:
<div id="menu" class="my-class">Click here to browse the internet.
<div id="envelope" class="my-class">
<div id="links" class="my-class">
<div>
<a id="g" class="redirect">
<img class="my-class" id="google" src="assets/google.png" />
</a>
</div>
<div style="width: 20%;"></div>
<div>
<a id="s" class="redirect">
<img id="sava" src="assets/Logo_Sava.png"/>
</a>
</div>
</div>
</div>
If you want to select everything you can use the below:
var areaa = document.querySelectorAll("#menu #envelope #links *");
If you want to be more specific you can do the following (the code below will select all of the anchor tags and images inside #links):
var areaa = document.querySelectorAll("#menu #envelope #links a, #menu #envelope #links img");
You can use querySelectorAll
The Document method querySelectorAll() returns a static (not live) NodeList representing a list of the document's elements that match the specified group of selectors.
Learn more: https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll
You can use it like this:
var areaa = document.querySelectorAll('*');
This will return all items.
You can replace document with the container if you want to restrict this to a specific div.
2 things, either add a class to every div
<div id="menu" class="area">Click here to browse the internet.
<div id="envelope" class="area">
<div id="links" class="area" >
<div>
<a id="g" class="redirect">
<img id="google" src="assets/google.png" />
</a>
</div>
<div style="width: 20%;"></div>
<div>
<a id="s" class="redirect">
<img id="sava" src="assets/Logo_Sava.png"/>
</a>
</div>
</div>
</div>
</div>
and select all divs by
let areaa = getElementsByClassName("area");
or you can use document.querySelectorAll("yourclassname") to access all divs of that class name

Jquery pass this.Text() as identifier

Basically im just trying to get the value of this.Text() and edit css of all class with that value.
<div>
<img class="First" style="display:none">
<img class="Second" style="display:none">
<img class="Third" style="display:none">
<p><span class="firstWord">First</span> phrase</p>
</div>
<div>
<img class="First" style="display:none">
<img class="Second" style="display:none">
<img class="Third" style="display:none">
<p><span class="firstWord">Second</span> phrase</p>
</div>
<div>
<img class="First" style="display:none">
<img class="Second" style="display:none">
<img class="Third" style="display:none">
<p><span class="firstWord">Third</span> phrase</p>
</div>
Im using this code to get the first word but im a bit lost on how to pass this.Text as indentifier. Im just trying to unhide an image with a class the same with the value of this.Text() :
$('.firstWord').each(function() {
fwtext = $(this).text();
$('#' $fwtext).css("display", "block");
});
The div and all tags inside it are dynamically generated and repeated so i cant simply go on editing them.
THANK YOU SO MUCH EVERYONE FOR HELPING.
This is wrong:
$('#' + $fwtext)
//-----^
Add a + for concatenation. Also since you are using a class and not an id, you must use . instead of #:
$('.' + $fwtext)
Your img tags have a class, not an id. So your jQuery selector should look like: $("." + fwtext). And yes - it will display necessary image only in corresponding div. jsFiddle for testing.
$(".firstWord").each(function () {
var fwtext = $(this).text();
var currentBlock = $(this).parents("div");
currentBlock.find("." + fwtext).show();
});
Remove the $ sign and add + in place of it
$('#'+ fwtext).css("display", "block");
based on your comment here is the edit
$('.firstWord').each(function() {
$('<div></div>').text($(this).text()).css("display", "block");
});

How to make a certain div visible while hovering an image?

<div class="parent">
<div class="parent.child">
<div class="parent.chil.child">
<div class="parent.chil.child.child">
<img src ="link0" >
<img src ="link1" >
<img src ="link2" >
</div>
</div>
</div>
<h4>
text
</h4>
<div class="imgClass0">
<p>some text</p>
</div>
<div class="imgClass1">
<p>some text</p>
</div>
<div class="imgClass2">
<p>some text</p>
</div>
Hey guys !
I have a problem. I have a div whithin I can have one or more <img> nodes, depends how the server generates the DOM (there can be one or many, depends on a number from the database.
There are several <div> elements under the <h4> node, the number of them is equal to the number of <img> elements from above.
I need help in making a javascript that makes "imgClass1" visible when I hover <img src ="link1" >, and the other imgClassX, X=(1..n) invisible, and so on. I give them default visibility display:none, but I need imgClass0 to have default visibility:visible.
Best regards,
iusmar.
You can attribute starts with selector along with :eq() selector:
$('img[src^=link]').hover(function() {
var idx = $(this).index();
$('div[class^="imgClass"]:eq(' + idx + ')').show();
}, function() {
var idx = $(this).index();
$('div[class^="imgClass"]:eq(' + idx + ')').hide();
});
Fiddle Demo
try like this
$("img[src=link1]").hover(function(){
$("div[class^='imgClass']").hide();
$(".imgClass1").show();
});
fiddle
First, you should put a class on your images to use as a selector. You should also put the image ID as a data attribute on the tags. This will allow you to easily assign an event handler when hovering these images, and also easily extract the image ID:
<img src="link0" class="yourImages" data-image-id="0">
<img src="link1" class="yourImages" data-image-id="1">
<img src="link2" class="yourImages" data-image-id="2">
You could also apply that ID to the divs:
<div class="images" data-image-id="0">
<p>some text</p>
</div>
<div class="images" data-image-id="1">
<p>some text</p>
</div>
<div class="images" data-image-id="2">
<p>some text</p>
</div>
Then you can bind a hover handler to the yourImages class, get the ID from the hovered element, hide all image divs then show only the required one:
$('.yourImages').hover(function() {
var imageID = $(this).data('image-id');
$('.images').hide();
$('.images[data-image-id="' + imageID + '"]').show();
}, function() {
$('.images').hide();
});
What do you want to do when you stop hovering over any images? My example just hides them all again.
Add a class / id just like following for the images
<img class="img0" src ="link0" >
<img class="img1" src ="link1" >
<img class="img2" src ="link2" >
and try the following javascript
$("img").hover(function (){
var cls=$(this).attr("class");
$("div[class^='imgClass']").hide();
var visibleCls=".imgClass"+(parseInt(cls.replace("img","")));
$(visibleCls).show();
});

How to get each element and assign them an inline style contained inside the child

I've been looking for an elegant solution for a day now and I am pretty new to jQuery.
I would like to get each .figure and assign them an inline style where the value is contained inside the child element via a custom data- attribute :
<div>
<a href="#">
<div class="figure">
<img class="thumbnail" data-thumbnail="images-01-thumbnail.png" src="images-01.png" />
</div>
<div class="content">
<h3>Sale</h3>
<h4>Discover our latest styles</h4>
</div>
</a>
<a href="#">
<div class="figure">
<img class="thumbnail" data-thumbnail="images-02-thumbnail.png" src="images-02.png" />
</div>
<div class="content">
<h3>Free Shipping</h3>
<h4>When you buy xxxxxx</h4>
</div>
</a>
<a href="#">
<div class="figure">
<img class="thumbnail" data-thumbnail="images-03-thumbnail.png" src="images-03.png" />
</div>
<div class="content">
<h3>Free Shipping</h3>
<h4>When you buy xxxxxx</h4>
</div>
</a>
</div>
In other words, the results would be :
...
<div class="figure" style="background: url(images-01-thumbnail.png);">
...
<div class="figure" style="background: url(images-02-thumbnail.png);">
...
<div class="figure" style="background: url(images-03-thumbnail.png);">
...
Also, I'm always ready something about jQuery so if you have any books about JavaScript or jQuery to suggest, that is always appreciated.
You can iterate over all .picture elements, find the image descendant and read its data attribute:
$('.figure').css('background', function() {
return 'url(' + $(this).children('img').data('thumbnail') + ')';
});
Some methods, like .css even accept functions so that you can iterate over the selected elements implicitly.
Reference: .css, .children, .data
you can iterate over each item with the class thumbnail and set the css property to the closet div.
$('.thumbnail').each(function() {
var $this = $(this),
$background = $this.data('thumbnail');
$this.closest('.figure').css({background : $background} )
});
This should work
$("[data-thumbnail]").each(function ()
{
var $this = $(this), url = $this.data("thumbnail");
$this.parents(".figure").css("background-image", 'url("' + url + '")');
});
How about this (Working code example: http://jsfiddle.net/jpbH2/2/):
var pathToImages = "/";
$(".figure img").each(function(){
$(this).parent().css({"background": "url(" + pathToImages + $(this).data('thumbnail') +")"})
});
Edit
I actually didn't notice the data-thumbnail. Edited my answer above

Combine two collections of elements with mobify.js

everyone.
I've just started using the mobifyjs toolkit and I've ran into a problem of combining two collections of elements into one.
On a page I'm trying to mobify there are two sets of links: with text and images. The HTML looks like the following:
<!-- links with text -->
<div id="products">
Product 1
Product 2
</div>
...
<!-- somewhere else on the page -->
<div id="productImages">
<img src="Product1.png />
<img src="Product2.png />
</div>
It needs to turn into the following:
<div class="items">
<div class="item">
<div class="img">
<img src="Product1.png />
</div>
<div class="title">
Product 1
</div>
</div>
<div class="item">
<div class="img">
<img src="Product2.png />
</div>
<div class="title">
Product 2
</div>
</div>
</div>
My current solution is to use map function, so in the mobify.konf I have something like the following:
'content': function(context) {
return context.choose(
{{
'templateName': 'products',
'products': function(){
return $('#productImages a').map(function() {
var href = $(this).attr('href') || '';
var div = $('<div class="item"><div class="img"></div><div class="title"></div></div>');
div.find('.img').append($(this).clone());
div.find('.title').append($('#products a[href="' + href + '"]').clone());
return div;
});
}
})
}
And the template is:
<div class="items">
{#content.products}
{.}
{/content.products}
</div>
This code does work but the approach itself is pretty ugly since I have to move a piece of markup code from the tmpl file into mobify.konf. Can anyone suggest a better solution?
The best way to do this sort of thing is to collect the relevant properties for your items (e.g. the product name, the image url and the link href) into a data structure in javascript, and then create a template for your new html structure in the .tmpl file. Something like
'products': function() {
var products = [],
$productLinks = $('#products a'),
$productImages = $('#productImages img')
len = $productNames.legnth;
for(var i = 0; i<len; i++) {
var $link = $productLinks.eq(i);
var $img = $productImages.eq(i);
products.push({name: $link.text(), href: $link.attr('href'), imgSrc: $img.attr('src')});
}
return products;
}
and then template it by iterating over the array items and inserting them into relevant places in the markup:
<div class="items">
{#content.products}
<div class="item">
<div class="img"><img src="{.imgSrc}" /></div>
<div class="title">{.name}</div>
</div>
{content.products}
</div>

Categories

Resources