The answer is below
I'm just starting to get into JQuery but I don't if I'm just slow understanding or stupid....
Let's say I wanna make a function where all my li objects... when you do a mouseover it gets the class name of the corresponding li element, and declaring a variable inside of it to keep that name, well my question is... how can I edit it with .css method and make a simple image swap ( image which is find through the class)
$("li")
.mouseover(function() {
var $myClass = $(this).attr("class");
var src = $($myClass).find('img').attr("src").match(/[^\.]+/) + "_over.png";
$("img"+ myClass).attr("src", src);
$($myClass).css("background-color", "#fff");
})
I don't know why it's not working, i'm guessing it's because my variable only display the name and not the actual name to edit it with jquery, I mean I don't know if it's adding the "." or "#" depending if it's a div or class for the code syntax, but I have no idea how to add that "." to the variable... or maybe it's because of my nested rules with my li objects, I mean to specifically refer to my li objects is:
#nav li
And yeah I know I'm telling solutions but I can't make em work :S
Anyone can help me?
**I did it haha! (What I was trying to do is change an <image> (with generic name) and class properties inside of a specific li object, knowing that li through their class when user triggers mouse over)
I'm just adding the code if anyone find this question helpful**.
$("li")
.mouseover(function() {
var $myClass = $(this).attr("class");
$myClass = "." + $myClass + " a";
var src = $($myClass).find('img').attr("src").match(/[^\.]+/) + "_over.png";
$myImg = $myClass + " img";
$($myImg).attr("src", src);
$($myClass).css("color", "#fff");
})
.mouseout(function() {
var $myClass = $(this).attr("class")
$myClass = "." + $myClass + " a";
var src = $($myClass).find('img').attr("src").replace("_over", "");
$myImg = $myClass + " img";
$($myImg).attr("src", src);
$($myClass).css("color", "#E3C922");
});
You can just do this in css:
.yourClass{
background: url(/path/image.jpg);
}
.yourClass:hover{
background: url(/path/image_over.jpg);
}
unless you have individual images for each li. Then you may want to clarify your needs so I can update this to a more useful answer.
just in case...
$("li")
.mouseover(function() {
var src = $(this).find('img').attr("src").match(/[^\.]+/) + "_over.png";
$(this).find("img").attr("src", src);
$(this).css("background-color", "#fff");
})
there's no reason to declare the myCLass var when you're within scope of that object alone. So you add the over state, then change the src of the img found and the li's background color.
An easy way to do this is to have one css class for the "li" element when it is not being hovered over and then another css class for when it is being hovered over with the background image set to whatever you want.
Then, in your jQuery you would use the removeClass() function and the addClass() function. The addClass() function would add the class with your hovered image.
Are you looking to change the class on mouse over?
$(li).mouseover(function{$(this).addClass("whatever");});
$(li).mouseout(function{$(this).removeClass("whatever");});
you can also use toggleClass() method
You can use the $varname method for variable declaration var keyword
Related
I have a pretty basic function that gets a result set of images based on search input
function appendSomeItems(url, id, name, style) {
return '<div><div class="md-card md-card-hover"><div class="gallery_grid_item md-card-content getImage"> <img class ="uk-align-center imageClick"></a><div class="gallery_grid_image_caption"> <span class="gallery_image_title uk-text-truncate">' + name + '</span> <span>' + style + '</span> </div></div></div></div>';
}
This works perfectly fine, and it is called in another function that basically gets up to 10 images from the result set and appends them in a div.
I have another function where I'm clicking one image and I want THAT specific image to clone and append to another div. The problem is, using class imageClick it clones and appends all images to the new div. If I change imageClick to an ID then it only clones/appends the first in the set.
How can I alter this to only clone and append the clicked image?
$(document).on('click', '.imageClick', function handleImage() {
console.log('good');
var img = $(".getImage").children("img").clone();
$("#holdImage").append(img);
});
Try .closest() on $(this) to target only the currently clicked image:
var img = $(this).closets(".getImage").children("img").clone();
Your current HTML suggest that you have only one image element which you are cloning. In this case finding children is meaningless. Simply cloning $(this) is enough:
var img = $(this).clone();
Use closest:
var img = $(this).closest(".getImage").children("img").clone(true);
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
<script type="text/javascript">
$(document).ready(function() {
ListUsers=function(em){
var emid = em.title;
$('.userslistdiv').text('id-' + emid);
$('.userslistdiv').show;
//alert("it worked-" + emid);
};
});
</script>
<div id="userslistdiv">xxxxxxxxx</div>
I'm not getting the changes to the div content. I get the alert if I uncomment it. I changed .show to .hide (since the div initially shows) and it does not "hide".
You have an id for the div, so need to use id selector(prefix #) not class selector(prefix .), also show is a method so you need to invoke it(add () at the end)
$(document).ready(function() {
ListUsers=function(em){
var emid = em.title;
$('#userslistdiv').text('id-' + emid);
$('#userslistdiv').show();
//alert("it worked-" + emid);
// both these can be combined to
//$('#userslistdiv').text('id-' + emid).show()
};
});
Change $('.userslistdiv').show; to $('.userslistdiv').show(); Add the parentheses.
Also, the DIV has an ID that's "userslistdiv"
Your code
$('.userslistdiv').text('id-' + emid);
$('.userslistdiv').show;
is attempting to find the class name.
Use this instead:
$('#userslistdiv').text('id-' + emid);
$('#userslistdiv').show();
Try:
<script type="text/javascript">
$(document).ready(function() {
ListUsers=function(em){
var emid = em.title;
$('#userslistdiv').text('id-' + emid);
//$('#userslistdiv').show();
//alert("it worked-" + emid);
};
});
</script>
<div id="userslistdiv">xxxxxxxxx</div>
For id use # for class use ..
Also, don't use show() unless the div is hidden.
You're referencing the element by id, not class, so
$('.userslistdiv')
should be
$('#userslistdiv')
and unrelated to the question, but please put a "var" in front of the variable when declaring it. This keeps it from polluting the global namespace.
Try this:
$(document).ready(function() {
$('#userslistdiv').text('it worked!');
});
I am looking to move or copy the contents of an HTML element. This has been asked before and I can get innerHTML() or Jquery's html() method to work, but I am trying to automate it.
If an element's ID begins with 'rep_', replace the contents of the element after the underscore.
So,
<div id="rep_target">
Hello World.
</div>
would replace:
<div id="target">
Hrm it doesn't seem to work..
</div>
I've tried:
$(document).ready(function() {
$('[id^="rep_"]').html(function() {
$(this).replaceAll($(this).replace('rep_', ''));
});
});
-and-
$(document).ready(function() {
$('[id^="rep_"]').each(function() {
$(this).replace('rep_', '').html($(this));
});
});
Neither seem to work, however, this does work, only manual:
var target = document.getElementById('rep_target').innerHTML;
document.getElementById('target').innerHTML = target;
Related, but this is only text.
JQuery replace all text for element containing string in id
You have two basic options for the first part: replace with an HTML string, or replace with actual elements.
Option #1: HTML
$('#target').html($('#rep_target').html());
Option #2: Elements
$('#target').empty().append($('#rep_target').children());
If you have no preference, the latter option is better, as the browser won't have to re-construct all the DOM bits (whenever the browser turns HTML in to elements, it takes work and thus affects performance; option #2 avoids that work by not making the browser create any new elements).
That should cover replacing the insides. You also want to change the ID of the element, and that has only one way (that I know)
var $this = $(this)
$this.attr($this.attr('id').replace('rep_', ''));
So, putting it all together, something like:
$('[id^="rep_"]').each(function() {
var $this = $(this)
// Get the ID without the "rep_" part
var nonRepId = $this.attr('id').replace('rep_', '');
// Clear the nonRep element, then add all of the rep element's children to it
$('#' + nonRepId).empty().append($this.children());
// Alternatively you could also do:
// $('#' + nonRepId).html($this.html());
// Change the ID
$this.attr(nonRepId);
// If you're done with with the repId element, you may want to delete it:
// $this.remove();
});
should do the trick. Hope that helps.
Get the id using the attr method, remove the prefix, create a selector from it, get the HTML code from the element, and return it from the function:
$('[id^="rep_"]').html(function() {
var id = $(this).attr('id');
id = id.replace('rep_', '');
var selector = '#' + id;
return $(selector).html();
});
Or simply:
$('[id^="rep_"]').html(function() {
return $('#' + $(this).attr('id').replace('rep_', '')).html();
});
From my question, my understanding is that you want to replace the id by removing the re-_ prefix and then change the content of that div. This script will do that.
$(document).ready(function() {
var items= $('[id^="rep_"]');
$.each(items,function(){
var item=$(this);
var currentid=item.attr("id");
var newId= currentid.substring(4,currentid.length);
item.attr("id",newId).html("This does not work");
alert("newid : "+newId);
});
});
Working Sample : http://jsfiddle.net/eh3RL/13/
I'm new to Javascript and am having a bit of an issue with using a NOT selector, and adding a class during the function, hopefully this will make sense to someone.
I am creating a small gallery, and my goal is to have clickable navigation, however the active image will redirect to another page when clicked.
Code is as follows:
$("ul#mainGallery li:not(.active) a").click(function(){
var thisListClass = $(this).parent().attr('class');
var activeListId = $(this).parent().attr('id');
var newMarginLeft = (activeListId-3) * -200;
var animateAction = {};
animateAction['margin-left'] = newMarginLeft + 'px';
$("ul#mainGallery").animate(animateAction, 1000);
$('li.active img').animate({width:'100px', height:'100px'},1000)
$(this + 'img').animate({width:'300px', height:'300px'},1000)
$(li.active).removeClass('active');
$(this).parent().addClass('active');
return false;
I know there is likely a much better way to do this, but I can't get my head around it.
Edit: I should probably say what the problem is...
When an active image is clicked, it follows the hyperlink all is well.
When a non active image is clicked, it begins the animation, then (i assume) when the 'active' class is added, instead of returning false, it returns true and follows the hyperlink.
You are binding the click event to $("ul#mainGallery li:not(.active) a") whenever that code is run (presumably on document load). The items which are not active at that point will have that item bound, and changing the class afterwards on other items won't bind this event to them. You will need to either change how you bind it or check inside the function whether the item has that class.
Something like this:
$("ul#mainGallery li a").click(function(){
if(!$(this).parent().hasClass('active')){
var thisListClass = $(this).parent().attr('class');
var activeListId = $(this).parent().attr('id');
var newMarginLeft = (activeListId-3) * -200;
var animateAction = {};
animateAction['margin-left'] = newMarginLeft + 'px';
$("ul#mainGallery").animate(animateAction, 1000);
$('li.active img').animate({width:'100px', height:'100px'},1000)
$(this + 'img').animate({width:'300px', height:'300px'},1000)
$('li.active').removeClass('active');
$(this).parent().addClass('active');
return false;
}
EDIT, or if you prefer to continue using the same selector with the :not and everything, then switch your click function to .live()
To stop the default behaviour use the preventDefault() function
$("ul#mainGallery li:not(.active) a").click(function(e){
e.preventDefault(); // will stop the default behaviour
}
Read more on Jquery docs