I need help switching background images with jQuery - javascript

I have an unordered list of img url's that are generated with from a custom post type in wordpress.
I have a slider and am using the number of slides to determine which Image url I want as the background for my element.
Sample of generated list:
<ul class="tes-image-links">
<li>http://img-url1</li>
<li>http://img-url2</li>
<li>http://img-url3</li>
</ul>
Sample of my jQuery
$('.cycle-slideshow').find('.cycle-slide').each(function(i){
if ( $(this).hasClass('cycle-slide-active') ){
var apimglink = $('.tes-image-links').children('li').eq(i).text();
$('.ap-testimonial.img-back').css("background" , "'url('"+apimglink+"') !important'" );
}
});
When I use console.log() it spits out the right text that is in the <li> tag, but I can't seem to get this to work.

Remove single quotes and !imprtant from background properties. Also dont forget to wrap your function in a DOM ready function
$(document).ready(function(){
$('.cycle-slideshow').find('.cycle-slide').each(function(i){
if ( $(this).hasClass('cycle-slide-active') ){
var apimglink = $('.tes-image-links').children('li').eq(i).text();
$('.ap-testimonial .img-back').css("background" , "url('"+apimglink+"')" );
}
});
})

The previous code is giving me issues and I could not get it to show the image with .each().
Using a for-loop I was able to get the Section to use the URL as a background based on the slide number:
var cycleSlide = $('.cycle-slideshow').find('.cycle-slide');
for (i = 0; i < cycleSlide.length; i++) {
if (cycleSlide.eq(i).hasClass('cycle-slide-active')){
var apimglink = $('.tes-image-links').children('li').eq(i).text();
apimglink = apimglink.replace("http://localhost", "");
$('.ap-testimonial').css('background-image', 'url(' + apimglink + ')');
console.log(apimglink);
} //End If
}; //End For
Thank you all for your help.

Related

Chrome is outputting something different than other browsers/IDE

Problem
I am making a wikipedia viewer for FreeCodeCamp. When I execute my code using Jetbrains Webstorm IDE, I get a total of 10 extra divs created at the end of my search results.
When I do so using JSfiddle, I see the correct results, which should just be the initial 10 search results, and not +10 more empty div containers.
Any idea what's going on?
Troubleshooting
After some more digging into it, it seems like this is more of a browser issue than an IDE issue. It looks like it's just Chrome that's doing this? I tried on Firefox and IE, and it runs as normal, just like the JSfiddle. I have also tried clearing all cookies and cache on Chrome.
When I open the console log and look at the elements, in Chrome, there are clearly 10 extra empty divs, as shown here.
But in Firefox, the same code does NOT create the divs, as shown here.
Edit: Okay, so in Chrome, if you hit enter, instead of clicking on the search button, it creates the extra divs. But if you click on the search icon, the results appear correctly. Can anyone explain why? Did I place/write the .keyup() code block incorrectly?
Here's a picture of said issue.
Javascript portion:
$(function(){
$("#search-bar").keyup(function(event) {
if(event.keyCode === 13) {
$(".btn").click();
}
});
$(".btn").click(function() {
$("#results").empty();
var searchTerm = $("#search-bar").val();
var url = "https://en.wikipedia.org/w/api.php?action=query&list=search&srsearch=" + searchTerm + "&utf8=&format=json&origin=*";
console.log(url);
$.ajax({
cache: false,
url: url,
type: 'GET',
success: function(data) {
// Create a blank array to store the specific URLs in
var urlArr = [];
for (var i=0; i <= data.query.search.length; i++) {
// Adding the variables for use here
var headerData = data.query.search[i].title;
var urlSearchTerm = headerData.replace(/\s/gi, '_');
var snippetData = data.query.search[i].snippet + "...";
var createDiv = document.createElement("div");
var createHeader = document.createElement("h1");
var createSnippet = document.createElement("p");
var divId = "div" + i.toString();
var headerId = "header" + i.toString();
var snippetId = "snippet" + i.toString();
var resultUrl = "https://en.wikipedia.org/wiki/";
urlArr[i] = resultUrl + urlSearchTerm;
// Create the div element, give it an id
// Create <h1> element, give it an id
// Create <p> element, give it an id
// Give each <div> a class
createDiv.setAttribute("id", divId);
createHeader.setAttribute("id", headerId);
createSnippet.setAttribute("id", snippetId);
createDiv.setAttribute("class", "each-result");
// appending <div> elements in the #results id element in body
// appending <h1> element to the div element
// appending <p> element to the div element
document.getElementById("results").appendChild(createDiv);
document.getElementById(divId).appendChild(createHeader);
document.getElementById(divId).appendChild(createSnippet);
// populate json data into <h1> element
// populate json data into <p> element
$("#header" + i.toString()).text(headerData);
$("#snippet" + i.toString()).html(snippetData);
// create a click event handler that does 2 things
// 1. Gives each div an element that has a URL in the resultUrl array
// 2. Opens that url in a new window
(function(i) {
$("#div" + i.toString()).click(function() {
window.open(urlArr[i]);
});
}(i));
}
}
});
});
$("#random-wiki-button").click(function() {
window.open("https://en.wikipedia.org/wiki/Special:Random");
});
});
Actual full code including html/css + JS: JSfiddle
Maybe try updating chrome?
I would try to change your for loop to for (var i=0; i < 10; i++) { that way the increment stops at the 10th item.
edited.

jQuery hover multiple ID's from php generated DIV

I'm having some troubles with a jQuery script.
I get my div's generated with PHP based on data from SQL.
echo "<div class='order' id='a$i' runat='server' draggable='true' >";
On mouseover it shows a different div also generated from PHP and SQL.
echo "<div class='position' id='b$i2' runat='server' draggable='true'>";
Then i have a jQuery script that has the hover function for the second div.
Every div get's it's ID from php. Menu div's get a1, a2, a3.... and hover div's get b1, b2, b3....
$(function() {
var moveLeft = 20;
var moveDown = 10;
var r = 1;
$('div#a'+r).hover(function(e) {
$('div#b'+r).show();
}, function() {
$('div#b'+r).hide();
});
$('div#a'+r).mousemove(function(e) {
$("div#b"+r).css('top', e.pageY + moveDown).css('left', e.pageX + moveLeft);
});
});
The code works for the first div, or the div i specify with the r variable.
I'm having troubles with code working for all the ID's on the page. They get generated based on SQL data.
https://postimg.org/image/ooqnfkx3n/
Is there a way to do this using LOOP function? Or getting the ID from generated div's?
Thanks for all the help in advance.
Use starts with selector
$("div[id^='a']").hover(function(event) {
//Do your thing
}
Documentation: Attribute Starts With Selector [name^=”value”]
How about you add the hover event on class instead of div but add logic based on div.
$(".theclassofA").hover(function(event) {
var id = $(this).attr('id');
var temp_rel = //then get the integer 'r' from this id
var temp_id = "b"+temp_rel;
//use this temp_id to show/hide your elements
}

How to convert links to text using JQuery?

I try to think up function which can replace links to text. Image inside a tag should be moved to the wrapper, the original a should be removed.
JS:
var selectors = 'a.mark-video;a.sp5;a>img[alt!=""]'
selectors = selectors.split(";").join(", ");
$(selectors).each(function() {
var current = this;
if (this.nodeName == "IMG") {
current = this.parentNode;
if (current.nodeName != "A")
current = this.parentNode;
if (current.nodeName != "A")
return false;
current = $(current);
}
var wrapper = current.parent();
var new_context = $().append(current.html());
current.remove();
wrapper.append(new_context);
}
);
The problem is
1) that the image is not inserted into the wrapper
2) if it would be inserted it would not have correct position.
I am experimenting using webextensions API (Firefox addon) and I injected the code to site:
http://zpravy.idnes.cz/zahranicni.aspx
In the debugger you can see two wrappers with class="art ". I have removed the first link but image is not inserted. The second one has not been removed yet when debugger was paused after first iteraction.
I hope you can find out why the image is not appended and how to append it to the original position of the element a. I need to find out position of the element a first, and then to move the image into to correct position - that is before div.art-info.
Note: please do not change the selectors string. This is the users input from form field.
Edit:
Almost there:
function(){
if (this.parentNode.nodeName == "A")
$(this.parentNode).replaceWith($(this));
else
$(this).html().replaceWith($(this)); // error: html() result does not have replaceWith...
}
Is this what you're looking for?
https://jsfiddle.net/4tmz92to/
var images = $('a > img');
$.each(images, function(key, image) {
$(this).parent().replaceWith(image);
});
First select all the images that you want to remove the link from, then loop through them and simply replace the parent() with the image.
I have finally solved the problem:
$(selectors).each(
function(){
if (this.parentNode.nodeName == "A")
$(this.parentNode).replaceWith($(this));
else
$(this).replaceWith(
$(this).html()
);
}
);
This works similar. Novocaine suggested not to use $(this).html() but this would skip some images so I prefer to use it.

js How to add href + text onclick

I need to pass (using javascript) text inside span to href
<div class='tableCell'><span>information</span></div>
<div class='tableCell'><span>contact</span></div>
<div class='tableCell'><span>about</span></div>
for example when i click to about link must be example.com/tag/about/
Here is my Answer. I'm using Javascript to manipulate the DOM to add a new element with the href equal to the inner text within the span element.
I hope you find this answer helpful.
Thanks.
var spans = document.getElementsByTagName('span')
var baseUrl = 'http://example.com/tag/'
for(var i=0; i<spans.length; i++)
{
var curElement = spans[i];
var parent = curElement.parentElement;
var newAElement = document.createElement('a');
var path = baseUrl+curElement.innerHTML;
newAElement.setAttribute('href', path);
newAElement.appendChild(curElement);
parent.appendChild(newAElement)
}
DEMO
The simplest way:
$( "span" ).click(function() {
var link = 'http://yousite.com/tag/'+ $(this).text().replace(/ /, "-")+"/";
window.location.href= link.toLowerCase();
});
DEMO
http://codepen.io/tuga/pen/yNyYPM
$(".tableCell span").click(function() {
var link = $(this).text(), // will provide "about"
href = "http://example.com/tag/"+link; // append to source url
window.location.href=href; // navigate to the page
});
You can try the above code
You do not have links but span in your html. However, you can get build the href you want and assign it to an existing link:
$('div.tableCell').click(function(){
var href = 'example.com/tag/' + $(this).find('span').text();
})
Lets work with pure javascript, I know you want to use jQuery but I am really sure too many people can't do this without looking in to web with pure javascript. So here is a good way.
You can follow it from jsFiddle
var objectList = document.getElementsByClassName("tableCell");
for(var x = 0; x < objectList.length; x++){
objectList[x].addEventListener('click', function(){
top.location.href = "example.com/tag/" + this.childNodes[0].innerHTML;
});
}
Lets work on the code,
var objectList = document.getElementsByClassName("tableCell");
now we have all element with the class tableCell. This is better than $(".tableCell") in too many cases.
Now objectList[x].addEventListener('click', function(){}); using this method we added events to each object.
top.location.href = "example.com/tag/" + this.childNodes[0].innerHTML; with this line if somebody clicks to our element with class: We will change the link to his first child node's text.
I hope it is useful, try to work with pure js if you want to improve your self.
Your Method
If you always are going to have the url start with something you can do something like this. The way it is set up is...
prefix + THE SPANS TEXT + suffix
spaces in THE SPANS TEXT will be converted to -
var prefix = 'http://example.com/tag/',
suffix = '/';
$('span').click(function () {
window.location.href = prefix + $(this).text().replace(' ', '-').trim().toLowerCase() + suffix;
//An example is: "http://example.com/tag/about-us/"
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='tableCell'><span>Information</span></div>
<div class='tableCell'><span>Contact</span></div>
<div class='tableCell'><span>About</span></div>
You can adjust this easily so if you want it to end in .html instead of /, you can change the suffix. This method will also allow you to make the spans have capitalized words and spaces.
JSBIN

Function when Elements className change

I am trying to change the background image of a section based on whatever slide has a particular classname.
I have an unordered list that is genereated with a loop
<ul class="tes-image-links">
<li>http://exampleimg1.jpg</li>
<li>http://exampleimg2.jpg</li>
<li>http://exampleimg3.jpg</li>
</ul>
I also have some javascript to change the background image of the section the unorderd list is contained in. The url for the background image depends on which div has the class name cycle-slide-active
var cycleSlide = $('.cycle-slideshow').find('.cycle-slide');
for (i = 0; i < cycleSlide.length; i++) {
if (cycleSlide.eq(i).hasClass('cycle-slide-active')){
var apimglink = $('.tes-image-links').children('li').eq(i).text();
apimglink = apimglink.replace("http://localhost", "");
$('.ap-testimonial').css('background-image', 'url(' + apimglink + ')');
console.log(apimglink);
} //End If
}; //End For
The above code gives me the right background image for whatever slide is first loaded, but after the slide changes nothing else happens.
I need help Executing the above code whenever cycleSlide.className for any cycleSlide element is changed.
Thank you all in advanced.

Categories

Resources