How to update 'src' attributes of multiple images? - javascript

I have the following source:
<body>
<div class="slideshow_top">
<img class="slideshow_image" src="img/cycle/putritos.jpg">
</div>
<div class="slideshow_mid">
<img class="slideshow_image" src="img/cycle/stage.jpg">
</div>
<div class="slideshow_bot">
<img class="slideshow_image" src="img/cycle/marketing.jpg">
</div>
...
</body>
Assuming I have three generated new src values such as:
var src1="img/cycle/newimage1.jpg
var src2="img/cycle/newimage2.jpg
var src3="img/cycle/newimage3.jpg
How can I change the source values of the already existing images? I'm unsure because I know the surrounding divs of the images are uniquely named, but the class of the images themselves are shared. Is it still possible to update each source attribute with Javascript given this?

Looks like part of your question has to do with selecting images only if they are a child of a slideshow_top/mid/bot div element. There's a few ways to do this...
In jQuery, you could do this:
$('.slideshow_top img').attr('src',src1);
$('.slideshow_min img').attr('src',src2);
//etc.
That's just a simple Sizzle CSS-style selector. You can also use jQuery's .children() method, if you want:
$('.slideshow_top').children('img').attr('src',src1);
In plain old JavaScript it's a little more wordy, but you can still do it:
var slideShowTop = document.getElementsByClassName('slideshow_top'),
slideShowTopImage = slideShowTop[0].getElementsByTagName('IMG');
slideShowTopImage[0].setAttribute('src',src1);
//etc.
Note though, that getElementsByClassName isn't supported in version of IE less than 9, so you'll have to write your own little function to, say, loop through all elements by tag name and filter them by className, etc. jQuery might be the way to go on this one...

You can do something like:
var new_images = $.map([1,2,3], function(x) { return "newimage" + x + ".jpg"; })
$("img").each(function(i, x) { x.src = new_images[i]; })

var src_array=["img/cycle/newimage1.jpg","img/cycle/newimage2.jpg","img/cycle/newimage3.jpg"]
$(".slideshow_image").each(function(index){
$(this).attr("src",src_array[index])
})

Try
.each( function(index, Element) )
Iterate over a jQuery object, executing a function for each matched element.
//create array of images
var arrSrc = ['img/cycle/newimage1.jpg','mg/cycle/newimage2.jpg','img/cycle/newimage3.jpg'];
$('.slideshow_bot .slideshow_image').each(function(i, el){ //to loop through images
el.prop('src',arrSrc[i]); //set image here
});
.prop( propertyName, value )

Related

Change location.href with jQuery

I need to change the location.href of some URLs on my site. These are product cards and they do not contain "a" (which would make this a lot easier).
Here is the HTML:
<div class="product-card " onclick="location.href='https://www.google.com'">
I mean it is pretty simple, but I just cannot get it to work. Did not find any results from Google without this type of results, all of which contain the "a":
$("a[href='http://www.google.com/']").attr('href', 'http://www.live.com/')
Any ideas on how to get this to work with jQuery (or simple JS)?
I cannot change the code itself unfortunaltely, I can just manipulate it with jQuery and JS.
To change the onClick for all the class='product-card', you can do something like this:
// All the links
const links = document.getElementsByClassName('product-card');
// Loop over them
Array.prototype.forEach.call(links, function(el) {
// Set new onClick
el.setAttribute("onClick", "location.href = 'http://www.live.com/'" );
});
<div class="product-card " onclick="location.href='https://www.google.com'">Test</div>
Will produce the following DOM:
<div class="product-card " onclick="location.href = 'http://www.live.com/'">Test</div>
Another option, is to loop over each <div> and check if something like google.com is present in the onClick, if so, we can safely change it without altering any other divs with the same class like so:
// All the divs (or any other element)
const allDivs = document.getElementsByTagName('div');
// For each
Array.from(allDivs).forEach(function(div) {
// If the 'onClick' contains 'google.com', lets change
const oc = div.getAttributeNode('onclick');
if (oc && oc.nodeValue.includes('google.com')) {
// Change onClick
div.setAttribute("onClick", "location.href = 'http://www.live.com/'" );
}
});
<div class="product-card" onclick="location.href='https://www.google.com'">Change me</div>
<div class="product-card">Don't touch me!</div>

How to use jQuery to select deeply nested elements created dynamically with javascript

So I have an object in my code and I use js to add the properties of the object to an array named rec based on users interaction. then I use a function named unRec to get unique elements of the array. Then I add the values returned by unRec to the HTML. Then I use jquery to wrap each of the values in anchor tags. So the code is basically like this
obj= {
0: "<span>module1</span>",
1: "<span>module1</span>",
2:"<span>module1</span>",
3:"<span>module2</span>",
4:"<span>module2</span>",
5:"<span>module3</span>",
6:"<span>module3</span>",
7:"<span>module3</span>",
8:"<span>module3</span>",
9:"<span>module4</span>"
}
function unRec(arr){
preRec = [];
for (j of arr){
if (preRec.indexOf(j)=== -1) {
preRec.push(j);
}
}
return (preRec);
}
Recom.innerHTML = unRec(rec);
$('#congrat #recom span').wrap('')
Now am unable to select the created anchors. Hence this function doesn't work
$('#congrat #recom .disp').click(function(e) {
var url = $(this).attr('href') + '#' + $(this).text();
$('#module').html('loading...).load(url); e.preventDefault();
});
I have tried to use find to select the anchors but it still doesn't work. This is the test
var t = $('#congrat #recom').find ('a').length;
console.log(t);
The HTML is basically like this:
<div id="congrat">
<span id="recom"></span>
</div>
<div id="module">click on one of the modules above<div>
Please provide a solution to select the created anchors. Thanks in advance

How to get class name of element has specific text using javascript/jquery?

I need a JavaScript or jQuery way of extracting the Class name of DIV element by the text it contains.
Let's illustrate. If I had let's say following code:
<div class="_className">UniqueText</div>
I need to to know how to programmatically do something like this:
getClassNameWhereText("UniqueText");
In this case output should be:
_className
Is there a way to do this?
JQuery :contains selector select element has specific text but it isn't exact. For example
$("div:contains(UniqueText)")
Select both of bottom divs
<div class="_className">UniqueText</div>
<div class="_className2">UniqueText2</div>
You can use .filter() to filter selected element by text.
var className = $("*").filter(function(){
return $(this).text() == "UniqueText";
}).attr("class");
var className = $("*").filter(function(){
return $(this).text() == "UniqueText";
}).attr("class");
console.log(className);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="_className">UniqueText</div>
<div class="_className2">UniqueText2</div>
By getting all the div with each function you can search through all the divs and place a condition in which you the value of the div is equal to the particular text that you want to find. Then get the class name by using .attr('class').
$( "div" ).each(function(){
if($(this).text() == "UniqueText"){
var output = $(this).attr('class');
$(".output").html(output);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="_classname">UniqueText</div>
<div class="output"></div>
It might be a bit long for a code but it gets the work done nicely. :)
You can use :contains(word)
var className = $( "div:contains('John')" ).attr("class");
console.log(className)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="foo">John Resig</div>
<div class="bar">George Martin</div>
<div class="foo">Malcom John Sinclair</div>
<div class="baz">J. Ohn</div>
You can keep an id for your div, as per your information your text will be unique.
<div id="UniqueText" class="_className">UniqueText</div>
and the js code will be
function getClassNameWhereText(text){
var className = $('#'+text).attr('class');
console.log(className);
}
UPDATE : if you want to using contains
then you can do this,
function getClassNameWhereText(text){
var val = document.getElementById(text).value;
if(text.indexOf(val)>=0){
var className = $('#'+text).attr('class');
console.log(className);
}
}
This should be faster than using jQuery (but a bit more to type):
var xpath = "//div[text()='UniqueText']";
var result = document.evaluate(xpath,
document, null, XPathResult.FIRST_ORDERED_NODE_TYPE);
var node = result.singleNodeValue;
if (node) {
console.log(node.className);
} else {
console.error("Not found!");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="_className">UniqueText</div>
The reason is, browser's CSS selectors don't support :contains selector, and jQuery needs to emulate it by checking every node matching the rest of the selector. Ditto for using .filter. But XPath is done natively by the browser.
You also cannot specify exact match using the jQuery :contains, like here. If substring matching was indeed needed, you can change the XPath:
var xpath = "//div[contains(text(),'UniqueText')]";
XPath is very powerful, but a bit finicky and largely unknown, so I find it is very under-utilised, even when its use would be a perfect fit.

how to repeat same Javascript code over multiple html elements

Note: Changed code so that images and texts are links.
Basically, I have 3 pictures all with the same class, different ID. I have a javascript code which I want to apply to all three pictures, except, the code needs to be SLIGHTLY different depending on the picture. Here is the html:
<div class=column1of4>
<img src="images/actual.jpg" id="first">
<div id="firsttext" class="spanlink"><p>lots of text</p></div>
</div>
<div class=column1of4>
<img src="images/fake.jpg" id="second">
<div id="moretext" class="spanlink"><p>more text</p></div>
</div>
<div class=column1of4>
<img src="images/real.jpg" id="eighth">
<div id="evenmoretext" class="spanlink"><p>even more text</p></div>
</div>
Here is the Javascript for the id="firsttext":
$('#firstextt').hide();
$('#first, #firsttext').hover(function(){
//in
$('#firsttext').show();
},function(){
//out
$('#firsttext').hide();
});
So when a user hovers over #first, #firsttext will appear. Then, I want it so that when a user hovers over #second, #moretext should appear, etc.
I've done programming in Python, I created a sudo code and basically it is this.
text = [#firsttext, #moretext, #evenmoretext]
picture = [#first, #second, #eighth]
for number in range.len(text) //over here, basically find out how many elements are in text
$('text[number]').hide();
$('text[number], picture[number]').hover(function(){
//in
$('text[number]').show();
},function(){
//out
$('text[number]').hide();
});
The syntax is probably way off, but that's just the sudo code. Can anyone help me make the actual Javascript code for it?
try this
$(".column1of4").hover(function(){
$(".spanlink").hide();
$(this).find(".spanlink").show();
});
Why not
$('.spanlink').hide();
$('.column1of4').hover(
function() {
// in
$(this).children('.spanlink').show();
},
function() {
// out
$(this).children('.spanlink').hide();
}
);
It doesn't even need the ids.
You can do it :
$('.column1of4').click(function(){
$(this); // the current object
$(this).children('img'); // img in the current object
});
or a loop :
$('.column1of4').each(function(){
...
});
Dont use Id as $('#id') for multiple events, use a .class or an [attribute] do this.
If you're using jQuery, this is quite easy to accomplish:
$('.column1of4 .spanlink').hide();
$('.column1of4 img').mouseenter(function(e){
e.stopPropagation();
$(this).parent().find('.spanlink').show();
});
$('.column1of4 img').mouseleave(function(e){
e.stopPropagation();
$(this).parent().find('.spanlink').hide();
});
Depending on your markup structure, you could use DOM traversing functions like .filter(), .find(), .next() to get to your selected node.
$(".column1of4").hover(function(){
$(".spanlink").hide();
$(this).find(".spanlink, img").show();
});
So, the way you would do this, given your html would look like:
$('.column1of4').on('mouseenter mouseleave', 'img, .spanlink', function(ev) {
$(ev.delegateTarget).find('.spanlink').toggle(ev.type === 'mouseenter');
}).find('.spanlink').hide();
But building on what you have:
var text = ['#firsttext', '#moretext', '#evenmoretext'];
var picture = ['#first', '#second', '#third'];
This is a traditional loop using a closure (it's better to define the function outside of the loop, but I'm going to leave it there for this):
// You could also do var length = text.length and replace the "3"
for ( var i = 0; i < 3; ++i ) {
// create a closure so that i isn't incremented when the event happens.
(function(i) {
$(text[i]).hide();
$([text[i], picture[i]].join(',')).hover(function() {
$(text[i]).show();
}, function() {
$(text[i]).hide();
});
})(i);
}
And the following is using $.each to iterate over the group.
$.each(text, function(i) {
$(text[i]).hide();
$([text[i], picture[i]].join(', ')).hover(function() {
$(text[i]).show();
}, function() {
$(text[i]).hide();
});
});
Here's a fiddle with all three versions. Just uncomment the one you want to test and give it a go.
I moved the image inside the div and used this code, a working example:
$('.column1of4').each(function(){
$('div', $(this)).each(function(){
$(this).hover(
function(){
//in
$('img', $(this)).show();
},
function(){
//out
$('img', $(this)).hide();
});
});
});
The general idea is 1) use a selector that isn't an ID so I can iterate over several elements without worrying if future elements will be added later 2) locate the div to hide/show based on location relational to $(this) (will only work if you repeat this structure in your markup) 3) move the image tag inside the div (if you don't, then the hover gets a little spazzy because the positioned is changed when the image is shown, therefore affecting whether the cursor is inside the div or not.
EDIT
Updated fiddle for additional requirements (see comments).

How to get inner HTML of element inside a list item, within a delegate?

I have this bit of HTML :
<li eventId="123">
<img src="image.jpeg"/>
<h3 id="eventName">Event Name</h3>
<p id="eventDescription"></p>
</li>
I want to be able to pull out the <h3> and <p> via jQuery so that I can update their values.
I have a delegate bound to the list items, and on click I'm trying to grab hold of <h3> and <p> using :
function eventIdClicked()
{
// This gets hold of "123" OK
theEvent.id = $(this).get(0).getAttribute('eventId');
// How to get the other 2 inner html?
var existingEventName = $(this).get(1).getAttribute('eventName');
var existingEventDesc = $(this).get(2).getAttribute('eventDescription');
$.mobile.changePage("home.html");
}
Am I able to do this?
Maybe something like $(this).find("h3").text() and $(this).find("p").text()?
Very simple jquery.
Also, while it isn't affecting the code in this case, ID's must be unique.
If the ID's aren't unique the elements might as well not have id's.
First off, in your case you should use classes instead of Id's if there are going to be multiple eventnames and eventdescriptions. As for the event handling try passing the event object into the function like so:
function eventIdClicked(evt){
// Now you get get the event target.
// In your case this is the li element.
var target = $(evt.target);
// Now you can pull out the children that you want.
var eventName = target.children(".eventName").text();
var eventDescription = target.children(".eventDescription").text();
// Do more stuff...
}
First, I take for granted that there are several of these <li> so you shouldn't use the id attribute as id have to be unique. I replaced these with a class name.
<li eventId="123">
<img src="image.jpeg"/>
<h3 class="name">Event Name</h3>
<p class="description"></p>
</li>
I cleaned up your syntax using cleaner jQuery methods. I also add the values to the object your are already referencing.
function eventIdClicked()
{
theEvent.id = $(this).attr('eventId');
theEvent.name = $('.name', this).text();
theEvent.description= $('.description', this).text();
$.mobile.changePage("home.html");
}
If you are using HTML5 this would be cleaner:
Replace <li eventId="123">
with <li data-event="{'id':123,'name':Event Name','description':'Event Description'}">
Replace
theEvent.id = $(this).attr('eventId');
theEvent.name = $('.name', this).text();
theEvent.description= $('.description', this).text();
with theEvent = $(this).data('event');
function eventIdClicked()
{
// This gets hold of "123" OK
theEvent.id = $(this).get(0).getAttribute('eventId');
// since you used an id for both tags, you could even ommit the context
var existingEventName = $("#eventName", this);
var existingEventDesc = $("#eventDescription", this);
existingEventName.text("a new event name");
existingEventDesc.text("a new description");
$.mobile.changePage("home.html");
}
Use children function:
var existingEventName = $(this).children('h3')
var existingEventDesc = $(this).children('p');
Now you can use text to grab or modify values. On the other hand those elements also have ids so you can access them using id selector.
If you want to change the innerHTML of the <h3> and <p>, you could use
$('#eventName').html(/*NEW HTML HERE*/);
$('#eventDescription').html(/*NEW HTML HERE*/);
This is assuming the ids are unique in your document

Categories

Resources