I have a page which has 3 sections. On the left a static menu
e.g.
<li>New File</li>
This can start new actions e.g.
$('.actionLink').click(function() {
var folderID; // trying set ID here
var fileName = $(this).attr('id');
$("#myAction").load('/ajax/actions/' + fileName + '.php?folder_id=' + folderID);
})
So, this loads /ajax/actions/newFile.php
In the middle is a page loaded using jquery .load(). Within the page in the middle is a series of folders which have an ID. On click, these folders display their contents are shown on the right of the page.
e.g.
<span id="12" class="folder active99">Music</span>
$('.folder').click(function() {
var folderID = $(this).attr('id');
$("#myAction").load('/ajax/actions/links.php?folder_id=' + folderID);
})
When clicked shows contents on the right. Note variable folderID. This all works ok.
What I would like to happen is when a folder is selected in the middle, it changes the folderID variable on the left hand menu so when a new action is chosen it corresponds to the folder its supposed to.
I've tried setting the variable everywhere i.e. in all sections var folderID; but whatever I try doesn't carry the variable around.
Is this possible or is there a better way to do this? Am I going about it wrongly?
To summarize: When I click a folder in the middle I need it to add the variable to the left menu.
UPDATE
This is code I currently use:
$(document).ready(function(){
var folderID = '';
$('.actionLink').click(function() {
var fileName = $(this).attr('id');
$("#myAction").load('/ajax/actions/' + fileName + '.php?folder_id=' + folderID);
});
$('.folder').click(function() {
$('.folder').removeClass('active99'); // remove from all other <SPAN>s
$(this).addClass('active99'); // add onto current
var folderID = $(this).attr('id');
$("#myAction").load('/ajax/actions/links.php?folder_id=' + folderID);
});
});
I've now changed things slightly so middle section is actually included as opposed to using .load() but still not working
You're dealing with a variable scope issue, you must declare the folderID variable outside (at a greater scope) so it's available for both actions:
$(document).ready(function(){
var folderID = '';
$('.actionLink').click(function() {
var fileName = $(this).attr('id');
$("#myAction").load('/ajax/actions/' + fileName + '.php?folder_id=' + folderID);
});
$('.folder').click(function() {
folderID = $(this).attr('id');
$("#myAction").load('/ajax/actions/links.php?folder_id=' + folderID);
});
});
Related
I'm trying to retrieve values set in chrome storage. The original value was stored using a different script in the same extension.
The value stored was stored using:
chrome.storage.sync.set({
logoStore: logolink})
Then I am using below to retrieve the storage value and replace the image url. No doubt the entirely incorrect method, syntax and all. :(
chrome.storage.local.get('logoStore', function (result) {
alert(logoStore.result);
});
var logourl = logoStore.result;
// ======= SWAP IMAGES ==========
var images = document.getElementsByTagName ("img");
var x=0;
while(x<images.length)
{
if(images[x].src == "https://www.this-url.com/images/new-brand-2016/common/logo-2016-246x48-v1.gif")
{
images[x].src = 'logourl';
}
x=x+1;
}
I'm very new to js, and have searched extensively on SO and elsewhere for the correct method to use the stored values. Sorry for such a noob question.
On an upnote - I did manage to resolve my last question with help and some further efforts myself :) Thanks.
========= UPDATE =========
I got this part working thanks to your input :)
Working code for this is...
chrome.storage.sync.get(['logoStore'], function(result) {
console.log('Value currently is ' + result.key);
var logourl = result.logoStore;
// ======= SWAP IMAGES ==========
var images = document.getElementsByTagName ("img");
var x=0;
while(x<images.length)
{
if(images[x].src == "https://www.url.com/images/new/common/logo-246x48-v1.gif")
{
images[x].src = logourl;
}
x=x+1;
}
});
Next Step...
Now I have to get two more values from storage and insert them into existing HTML.
I can successfully get the first value to load, but it is breaking my inline style, and the second value is not loading.
Code below.
// ========== ADD HEADER TEXT ==============
chrome.storage.sync.get(['companyStore', 'dataStore'], function(result) {
console.log('Value currently is ' + result.key);
var company = result.companyStore;
var data = result.dataStore;
var el = document.querySelector('table.delivery-address');
// get element content as string
console.log(el.innerHTML)
// prepend to the element's content
el.innerHTML = '</table><div style="margin-right:0px;float:right;text-align:right;margin-top:20px;"><h2 style="font-size: 28px;">Info</h2><br/><p style="font-size:18px;line-height:1.4em;"><b>' + company; + '</b><br/>' + data; + '<b></p></div><br/><br/><table class="delivery-address">' + el.innerHTML;
});
I am trying to have a div element on every page of my site that will contain the product number and then have a link that will put that number at the end.
For example,
<div id="productnumber">01101</div>
https://example.com/#
Then put the contents of the element with id "productnumber" after the # of the link.
Any idea if this is possible? Since this would make life easier than editing all existing pages and their respective php files.
Check for Element.innerHTML. You could use some inline JS and append it to the href-Attribute (which should be were id="purchaseurl" is now)
You can add a simple script to all your pages.
document.addEventListener("DOMContentLoaded", function() {
var productNumber = document.getElementById('productnumber').textContent;
Array.prototype.forEach.call(document.querySelectorAll('a[href~="purchaseurl"]'), function(link) {
// if you want to change the link
var currentHref = link.getAttribute('href');
link.setAttribute('href', currentHref + '#' + productNumber);
// if you want to change anchor text
var currentText = link.innerHTML;
link.innerHTML = currentText + productNumber;
});
});
<div id="productnumber">01101</div>
https://example.com/#
See getElementById, getElementsByTagName, and nextSibling.
var data = document.getElementById('productnumber'),
url = data.nextSibling.nextSibling;
url.innerText += data.innerText;
<div id="productnumber">01101</div>
https://example.com/#
I am struggling with a list that can be drag/dropped and nested.
How it should work :
1.Each row has an "add line" button.
2.When this button is clicked, I am trying to insert a new line, which is a text box, directly below/after the element where the button was clicked
3.Then get/add a unique ID for the new element/row.
4.Lastly once typing text in the new elements text box, get this text (to post to server).
The Javascript looks like this now :
$(document).on('click', '#addLabel_Item', function () {
var tree_id = ($(this).prop("title"));
var $tree_box = '#' + tree_id;
var $tree_box_item = '#' + tree_id + ' li';
var currentListItem = $(this).closest(".listed").attr("id");
var $items=$('.listed');
var parentID = $items.index($(this).closest(".listed"));
$("#list_reference_2").show();
//$("#list_reference_2").clone(true).insertAfter($("li").closest("ol#top_list_items li:eq(" + parentID + ")"));
//$("#list_reference_2").clone().insertAfter('ol > li:nth-child(1)');
$("#list_reference_2").clone().insertAfter("ol li:eq(" + parentID + ")");
});
Right now if I click to add a new line, it adds to the proper place on the initial/first click on the button. However, subsequent clicking on a different button adds the lines under the initial/first row rather than under the current one just clicked.
Fiddle showing what it does
Apologies if my explanation is confusing, I am confusing myself a bit :-)
Any help or point in the right direction would be greatly appreciated.
You can add the lines in this way:
$(document).on('click', '#addLabel_Item', function () {
var $li = $(this).closest('.listed');
$("#list_reference_2").show();
$li.after($("#list_reference_2").clone().removeAttr('id'));
$("#list_reference_2").hide();
});
JSFiddle: http://jsfiddle.net/tx7hbkjL/15/
PS: Take a look at your duplicate IDs, like #addLabel_Item. IDs must be unique in the page, use class instead.
Give it a try and let me know if it helps!
I understand that this question has been answered before, but even after consulting those links, I am still unable to solve my problem. I want to replace my image (assets/img/social-mail.jpg) to another (assets/img/social-mail-hover.jpg), with a single class, because I have multiple images I would like to do this to. My basic thought process is this: When the class is hovered, take the ID, and replace its image with another by adding "-hover" to its image link.
HTML:
<img id="social-mail" class="box-social" src="assets/img/social-mail.jpg">
JS:
$(".box-social").hover(function(e) {
var id = $(this).attr("id");
var icon = id.split("-")[1];
var image = "img/social-" + icon + "-hover.jpg";
$(id).find("img").attr("src", image);
});
I've tested id, icon, and image; and they all give me exactly what I want. However, when I hover over the image, it still isn't being replaced. I'm not getting any errors either. What am I doing wrong? Thank you so much!
I think there are at least four problems with your function:
To select by element id you need the # prefix, so $("#" + id) not $(id).
You don't want .find() because this is already the image in question.
Your image path in the html begins with "assets" but you don't include that in your Javascript.
If you only supply one funtion to .hover() that function will be called both when the mouse moves in and when it moves out. So you never change the image back.
The four lines of your function can be replaced with one line:
$(".box-social").hover(function(e) {
this.src = "assets/img/" + this.id + "-hover.jpg";
});
This fixes problems 1-3 above. To fix problem 4 just supply a second function to change the src back when the mouse leaves:
$(".box-social").hover(function(e) {
this.src = "assets/img/" + this.id + "-hover.jpg";
}, function(e) {
this.src = "assets/img/" + this.id + ".jpg";
});
You need to correct your selector.
JS:
$(".box-social").hover(function (e) {
var id = $(this).attr("id");
var icon = id.split("-")[1];
var image = "assets/img/social-" + icon + "-hover.jpg"; //make sure the path is correct
$('#' + id).attr("src", image); //Changed the selector.
});
Demo:http://jsfiddle.net/GCu2D/521/
try this
$(".box-social").hover(function(e) {
var id = $(this).attr("id");
var icon = id.split("-")[1];
var image = "assets/img/social-" + icon + "-hover.jpg";
$("#"+id).attr("src", image);
});
you forgot "assets/" in your image link and your img selector is not corresct
im new to jquery bbq, i've figured out most of the setup so far but i have a little issue. heres the setup.
one page with main nav links on the right
each nav link click will change the body content of the page to its corresponding data (showing and hiding divs) (with bbq)
one of the links shows a div with another set of links that when clicked will set hash B in the url
so first link click
domain.com/dir/#A=page1
second link click
domain.com/dir/#A=page1&B=set1
if i press the back button it goes back to the previous A hash, however the B hash remains in the url.
is there a way to remove the B peram when not on the specific page?
$(window).bind('hashchange', function(e) {
var state = $.bbq.getState('p');
var graphState = $.bbq.getState('n');
var base_title = '{/literal}{$smarty.const.SITE_TITLE}{literal} | Dashboard | ';
$('.profile-nav a').each(function() {
if (!state) {
$('.profile-nav a').each(function() {
$('#' + this.id).removeClass('live active');
document.title = base_title + 'Message Center';
});
$('#m').addClass('live active');
} else if (state == this.id) {
$('#' + this.id).addClass('live active');
document.title = base_title + $(this).text();
} else {
$('#' + this.id).removeClass('live active');
}
});
if (!state) {
$('.tab-content').fadeOut('fast');
$('.message-content').fadeIn('slow');
} else {
$('.tab-content').fadeOut('fast');
clicked = $('#' + state).attr('rel').split(' ')[0];
$('.' + clicked).fadeIn('slow');
}
if (state == 'r') {
if (graphState) {
$('.nick-breakdown').fadeOut('fast');
$('#' + graphState).fadeIn('slow');
document.title = base_title + 'Reports | ' + $('#' + graphState).attr('rel');
} else {
$('.item-breakdown').fadeOut('fast');
$('.nick-breakdown').fadeIn('slow');
document.title = base_title + 'Reports';
}
}
});
I've accomplished the same thing using jsbbq.pushState with merge_mode = 2 instead of just setting the # on the anchor.
Check out the docs here: http://benalman.com/code/projects/jquery-bbq/docs/files/jquery-ba-bbq-js.html#jQuery.bbq.pushState
merge_mode(Number) : Merge behavior defaults to 0 if merge_mode is not
specified (unless a hash string beginning with # is specified, in
which case merge behavior defaults to 2), and is as-follows:
0: params in the params argument will override any params in the current state.
1: any params in the current state will override params in the params argument.
2: params argument will completely replace current state.
So if your link looks like:
mysite.com#A=page1&B=page2 you could call
$.bbq.pushState({'A' : 'pageXYZ'}, 2);
And your doc location would then be:
mysite.com#A=pageXYZ
I got a way easier approach, no plugins needed:
Copy over current hashparameters to a dummy URL AS searchParameters. Now you can treat the hash parameters like search-parameters, edit them with all the functionality of searchparameters (developer.mozilla.org/en-US/docs/Web/API/URLSearchParams) and copy them back afterwards AS hasparameters,
E.g Simple function that set and updates parameters, you could also use '.delete()' instead of '.set' to delete the parameter:
function setOrUpdateHashParameter( hashParameterName, hashParameterValue ) {
let theURL = new URL('https://dummy.com'); // create dummy url
theURL.search = window.location.hash.substring(1); // copy current hash-parameters without the '#' AS search-parameters
theURL.searchParams.set( hashParameterName, hashParameterValue ); // set or update value with the searchParams-API
window.location.hash = theURL.searchParams; // Write back as hashparameters
}
If anyone knows how to format these post properly, feel free to edit it, thanks!